C++ primer 第五版 中文版 练习 10.20 个人code

来源:互联网 发布:md5算法c语言实现 编辑:程序博客网 时间:2024/06/05 11:28

C++ primer 第五版 中文版 练习 10.20

题目:标准库定义了一个名为 count_if 的算法。类似find_if,此函数接受一对迭代器,表示一个输入范围,还接受一个谓词,
会对输入范围中每个元素执行。count_if返回一个计数值,表示谓词有多少次为真。使用count_if重写我们的程序中统计有多少单词长度超过6的部分。


答:

/*标准库定义了一个名为 count_if 的算法。类似find_if,此函数接受一对迭代器,表示一个输入范围,还接受一个谓词,会对输入范围中每个元素执行。count_if返回一个计数值,表示谓词有多少次为真。使用count_if重写我们的程序中统计有多少单词长度超过6的部分。*/#include <iostream>#include <algorithm>#include <string>#include <vector>using namespace std;bool isShorter(const string &s1, const string &s2){return s1.size() < s2.size();}void elimDups(vector<string> &words){sort(words.begin(), words.end());cout << "vector用sort重排后的元素内容为:";for (auto a : words)cout << a << " ";cout << endl;auto end_unique = unique(words.begin(), words.end());cout << "vector用unique重排后的元素内容为:";for (auto a : words)cout << a << " ";cout << endl;words.erase(end_unique, words.end());cout << "vector中删除重复元素后的内容为:";for (auto a : words)cout << a << " ";cout << endl;}string make_plural(size_t ctr, const string &word, const string &ending){return (ctr > 1) ? word + ending : word;}void biggies(vector<string> &words, vector<string>::size_type sz){elimDups(words);stable_sort(words.begin(), words.end(), [](const string &a, const string &b){return a.size() < b.size(); });auto cnt = count_if(words.begin(), words.end(), [sz](const string &s){return s.size()>=sz; });cout << cnt << " " << make_plural(cnt, "word", "s") << " of length " << sz << " or longer" << endl;cout << endl;}int main(){vector<string> svect = { "the", "quick", "red", "fox", "jumps", "over", "the", "slow", "red", "turtle" };biggies(svect, 6);return 0;}


0 0
原创粉丝点击