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;
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;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值