第十章 10.3.4节练习

练习10.22

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

解答:

<pre name="code" class="cpp">#include <iostream>
#include <algorithm>
#include <functional>
bool check_size(const string &s, string::size_type sz){
    return s.size() >= sz;
}

int main(){
    using namespace std::placeholders;
    string s("hello");
    auto check6 = bind(check_size, _1, 6);//可以使用check6(s)进行调用。
// ...

 

以上是测试程序,现将要绑定的函数写好,在将函数绑定。

auto wc = find_if(words.begin(), words.end(), bind(check_size, _1, sz));
替换原有的find_if语句。


练习10.23

bind接受几个参数?

解答:

从cplusplus reference中得到的答案是N个(N为自然数)。

在vs2013的IDE中,能自动联想出来20个。

自认为20个已经就够用了,一般自己的程序参数不会超过5个。


练习10.24

给定一个string,使用bind和check_size在一个int的vector中查找第一个大于string长度的值。

解答:

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <functional>

using namespace std;

bool check_size(const string &s, string::size_type sz){
	return s.size() < sz;
}

int main(){
	using namespace std::placeholders;
	string s("hello");
	auto checkN = bind(check_size, s, _1);

	vector<int> num{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	for (auto iter = num.begin(); iter != num.end(); ++iter){
		if (checkN(*iter)){
			cout << *iter << " is the first element larger than string length" << endl;
			break;
		}
	}
}


练习10.25

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

解答:

这道题和10.22类似

将相关函数补充好之后,将下面的代码替换对应位置的代码即可

auto wc = partition(words.begin(), words.end(), bind(check_size, _1, sz));


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值