第十章 10.3.3节练习

练习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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值