练习10.20 标准库定义了一个名为count_if的算法。类似find_if,此函数接受一对迭代器,表示一个输入范围,还接受一个谓词,会对输入范围中每个元素执行。count_if返回一个计数值,表示谓词有多少次为真。使用count_if重写我们程序中统计有多少单词长度超过6的部分。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void biggies(vector<string> &, vector<string>::size_type);
void elimDups(vector<string> &);
int main()
{
vector<string> text;
string word;
while (cin >> word) {
text.push_back(word);
}
biggies(text, 6);
return 0;
}
void elimDups(vector<string> &text) // 抹去相同的单词(题目好像没要求这样做啊。。。。算了 写都写了)
{
sort(text.begin(), text.end());
auto iter = unique(text.begin(), text.end());
text.erase(iter, text.end());
}
void biggies(vector<string> &text, vector<string>::size_type sz) // 找出大于等于6个字符的单词 并打印
{
elimDups(text);
auto cnt = count_if(text.begin(), text.end(), [sz](const string &s) {return s.size() >= sz; });
cout << cnt << " word(s) no less than six ." << endl;
}
练习10.21 编写一个lambda,捕获一个局部Int变量,并递减变量值,直至它变为0。一旦变量变为0,再调用lambda应该不再递减变量。lambda应该返回一个bool值,指出捕获 的变量是否为0。
#include <iostream>
using namespace std;
int main()
{
int val = 7;
auto f = [&val]()->bool { return val == 0 ? false : true; };
while (--val) {
;
};
if (f() == false) {
cout << "function succeed" << endl;
}
else {
cout << "falsed." << endl;
}
return 0;
}