#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 turtle
vector<string> words;
vector<string>::iterator noUnique;
//将单词添加入vector
words.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;
}
对容器元素进行排序
最新推荐文章于 2024-04-01 22:03:30 发布