10.20
#include <iostream> #include <algorithm> #include <vector> using namespace std; int larger(vector<string> &words, vector<string>::size_type sz) { int cnt = count_if(words.cbegin(), words.cend(), [sz](const string &s) -> bool { return s.size() > sz; }); return cnt; } int main() { vector<string> words; string word; while (cin >> word) { words.push_back(word); } auto cnt = larger(words, 4); cout << cnt << endl; return 0; }10.21
#include <iostream> #include <algorithm> using namespace std; void dec(int para) { int i = para; auto f = [&i]() -> bool { if ( i > 0 ) { --i; return false; } else { return true; } }; for (int j = 0; j < para + 1; j++) cout << f() << " "; cout << endl; } int main() { dec(4); return 0; }10.22
#include <iostream> #include <vector> #include <algorithm> #include <functional> using namespace std; using namespace std::placeholders; bool check_size(const string &s, string::size_type sz) { return s.size() <= sz; } int count(vector<string> &s, string::size_type sz) { auto cnt = count_if(s.begin(), s.end(), bind(check_size, _1, sz)); return cnt; } int main() { vector<string> words; string word; while (cin >> word) words.push_back(word); auto cnt = count(words, 6); cout << cnt << endl; return 0; }10.23 bind一般形式:auto newCallable = bind(callable, arg_list); arg_list是逗号分隔的参数列表,对应给定的callable的参数。
10.24
#include <iostream> #include <algorithm> #include <functional> using namespace std; using namespace std::placeholders; bool isLonger(const string &s, string::size_type sz) { return s.size() < sz; } int main() { vector<int> ivec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; string s; cin >> s; auto wc = find_if(ivec.begin(), ivec.end(), bind(isLonger, s, _1)); cout << "val = " << *wc << endl; return 0; }10.25
bool check_size(const string &s, string::size_type sz) { return s.size() >= sz; } 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 = stable_partition(words.begin(), words.end(), bind(check_size, _1, sz)); auto cnt = wc - words.begin(); for_each(words.begin(), wc, [](const string &s) { cout << s << " "; }); cout << endl; }