10.3.4节练习

练习10.22 重写统计长度小于等于6的单词数量的程序,使用函数代替lambda。

#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;
using namespace std::placeholders;
bool func(const string &, vector<string>::size_type);
int main()
{
	vector<string> text;
	string word;
	while (cin >> word) {
		text.push_back(word);
	}

	auto cnt = count_if(text.begin(), text.end(), bind(func, _1, 6));
	cout << "the text you worte which has " << cnt << " word(s) no longer than 6" << endl;
	return 0;
}
bool func(const string &s, vector<string>::size_type sz)
{
	return s.size() <= sz;
}


练习10.23 bind接受几个参数?

答:bind可接受的参数依赖于算法传递给他的参数个数。


练习10.24 给定一个string,使用bind和check_6在一个Int的vector中查找第一个大于string长度的值。

#include <iostream>
#include <vector>
#include <string>
#include <functional>
#include <algorithm>
using namespace std;
using namespace std::placeholders;
bool check_size(const string &, const int i);
int main()
{
	vector<int> val{ 0,1,2,3,4,5,6,7,8,9,10 };
	string s = "tiger";
	auto iter = find_if(val.cbegin(), val.cend(), bind(check_size, s, _1));
	cout << "the value is SIX ?   " << *iter << endl;
	return 0;
}
bool check_size(const string &s, const int i) // bind的参数是vector<int>中的元素,然后找出第一个大于5的值。
{
	return s.size() < i;

}


练习10.25 在10.3.2节(第349页)的联系中,编写了一个使用partition的biggies版本。使用check_size和bind重写次函数。

// 打印长度大于等于5的string元素
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
using namespace std::placeholders;
bool check_size(const string &, vector<string>::size_type);
int main()
{
	vector<string> text;
	string word;
	while (cin >> word) {
		text.push_back(word);
	}
	auto iter = partition(text.begin(), text.end(), bind(check_size, _1, 5));
	//一个打印按字典顺序排序的算法
	for_each(text.begin(), iter, [](const string &s) {cout << s << " "; });
	cout << endl;
	return 0;
}
bool check_size(const string &s, vector<string>::size_type sz)
{
	return s.size() >= 5;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值