练习10.20:
标准库定义了一个名为count_if的算法。类似find_if,此函数接受一对迭代器,表示一个输入范围,还接受一个为此,会对输入范围中每个元素执行。
count_if返回一个计算数值,表示谓词多少次为真。使用count_if重写我们程序中统计有多少单词长度超过6的部分。
解答:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main(){
vector<string> test{ "hello", "world", "google", "baidu", "MiUi", "Nature", "abcdefg"};
auto count = count_if(test.cbegin(), test.cend(), [](const string &a){
return a.size() >= 6; });
cout << count << endl;
}
可以把这道题当做一个新题重新写。
然后,再将原来代码的对应部分进行替换。
练习10.21:
编写一个lambda,捕获一个局部int变量,并地接变量值,直至它变为0,一旦变量变为0,在调用lambda应该不在递减变量。lambda应该返回一个bool值,指出捕获的变量是否为0.
解答:
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int dec = 100;
auto lambda = [&](){
while (--dec);
return (dec == 0);
};
cout << lambda() << endl;
}
这里的确为0.