C++容器排序算法的简单应用

来源:互联网 发布:通达信软件电脑版 编辑:程序博客网 时间:2024/05/01 11:58
/*功能实现1.去掉所有重复的单词2.按照单词的长度进行排序3.统计长度等于或者超过6个字符的单词个数4.按照单词的长度顺序进行输出*/#include <iostream>#include <algorithm>#include <string>#include <vector>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(vector<string>::size_type cnt , string s1 , string s2){return (cnt == 1) ? s1 : s1+s2;  }int main(){typedef vector<string>::iterator iter;typedef vector<string>::size_type sz_type;vector<string> words;string next_word;//输入单词while(cin >> next_word && next_word != "0"){//当输入0时结束words.push_back(next_word);}//对单词进行排序,按照字典序进行排列sort(words.begin() , words.end());//去掉重复的单词iter end_unique = unique(words.begin() , words.end());words.erase(end_unique , words.end());//对剩下没有重复的单词进行长度排序,长度相等的进行字典序排列stable_sort(words.begin() , words.end() , isShorter);//按长度输出剩下的单词for(iter it = words.begin() ; it != words.end() ; ++it){cout << *it  << "  ";}cout << endl;//找到单词长度大于等于6个字符的个数sz_type wc = count_if(words.begin() , words.end() , GT6);cout << wc << make_plural(wc , "time" , "s") << endl;return 0;}