泛型算法05

来源:互联网 发布:惠普打印机安卓软件 编辑:程序博客网 时间:2024/06/10 16:03
/*编写程序统计长度不小于4的单词,并输出输入序列中不重复的单词。在程序源文件上运行和测试你自己的程序*/#include<iostream>#include<vector>#include<fstream>#include<algorithm>//count函数#include<string>using namespace std;//用于长度比较的排序函数bool isShorter(const string&s1, const string&s2){return s1.size() < s2.size();}//用于判断给定的单词是否小于4bool GT4(const string&s){return s.size() >= 4;}//若ctr不为1,返回word的复数版本string make_plural(size_t ctr, const string &word, const string &ending){return (ctr == 1) ? word : word + ending;//??}void function(){string text;cin >> text;ifstream inFile(text.c_str());if (!inFile){cerr << "Can not open input file!" << endl;return ;}//读入word进入vectorvector<string> words;string word;while (inFile>>word){words.push_back(word);}//排序以便除去重复的单词sort(words.begin(),words.end());//使用unique算法对元素重新排序并返回一个迭代器//表示无重复的单词范围的结束//erase操作,使用迭代器删除输入序列中重复的单词words.erase(unique(words.begin(),words.end()),words.end());//将单词按长度排序,等长的单词按照字母排序stable_sort(words.begin(), words.end(), isShorter);//计算并输出长度不小于4的单词数目vector<string>::size_type wc = count_if(words.begin(), words.end(), GT4);cout << wc << " " << make_plural(wc, "word", "s")<< " 4 characters or longer" << endl;//输出不重的单词cout << "unique words:" << endl;for (vector<string>::iterator iter = words.begin(); iter != words.end();++iter){cout << *iter << " ";}cout << endl;}

0 0
原创粉丝点击