练习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));