对容器元素进行排序
来源:互联网 发布:jsp php asp.net 编辑:程序博客网 时间:2024/05/21 07:54
#include <list>#include <vector>#include <string>#include <algorithm>#include <iterator>#include <iostream>using namespace std;bool isShorter(const string &s1,const string &s2){return s1.size()<s2.size();}bool GT6(const string &s){return s.size()>=6;}string make_plural(size_t ctr,const string &word, const string &ending){return (ctr==1)?word:word+ending;//make_plural(wc, "word ", "s ")当输入中文本中 //word数大于一是在word后加s,为words为word的复数!}int main(){//words:the quick red fox jumps over the slow red turtlevector<string> words;vector<string>::iterator noUnique;//将单词添加入vectorwords.push_back(string("the"));words.push_back(string("quick"));words.push_back(string("red"));words.push_back(string("fox"));words.push_back(string("jumps"));words.push_back(string("over"));words.push_back(string("the"));words.push_back(string("slow"));words.push_back(string("red"));words.push_back(string("turtle"));//原样输出单词cout<<"before sort:"<<endl;cout<<"----------------------------"<<endl;for (vector<string>::iterator iter=words.begin();iter!=words.end();++iter){cout << *iter<<endl;}cout<<"----------------------------"<<endl;//排序,然后输出sort(words.begin(),words.end());cout<<"after sort:"<<endl;cout<<"----------------------------"<<endl;for (iter=words.begin();iter!=words.end();++iter){cout << *iter<<endl;}cout<<"----------------------------"<<endl;//去除重复,然后输出noUnique=unique(words.begin(),words.end());//将无重复的元素复制到序列的前端,返回的迭代器指向超出无重复元素范围末端的下一个位置words.erase(noUnique,words.end());//去除重复的元素cout<<"after unique:"<<endl;cout<<"----------------------------"<<endl;for (iter=words.begin();iter!=words.end();++iter){cout << *iter<<endl;}cout<<"----------------------------"<<endl;//按照字符数长度排序,找出长度大于6的元素个数,并将其输出stable_sort(words.begin(),words.end(),isShorter);vector<string>::size_type wc=count_if(words.begin(),words.end(),GT6);cout<<wc<<" "<<make_plural(wc,"word","s")<<" 6 characters or longer"<<endl;for (iter=words.begin();iter!=words.end();++iter){if (GT6(*iter)){cout << *iter<<endl;}}cout<<"----------------------------"<<endl;return 0;}