#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;
}