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

来源:互联网 发布:mac搜狗输入法用不了 编辑:程序博客网 时间:2024/05/16 10:57

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

题目:重写biggies,用partition代替find_if。我们在10.3.1节练习中介绍了partition算法。

答:

/*重写biggies,用partition代替find_if。我们在10.3.1节练习中介绍了partition算法。*/#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 wc = partition(words.begin(), words.end(), [sz](const string &a){return a.size() < sz; });auto count = words.end() - wc;cout << count << " " << make_plural(count, "word", "s") << " of length " << sz << " or longer" << endl;for_each(wc, words.end(), [](const string &s){cout << s << " "; });cout << endl;}int main(){vector<string> svect = { "the", "quick", "red", "fox", "jumps", "over", "the", "slow", "red", "turtle" };biggies(svect, 4);return 0;}


0 0
原创粉丝点击