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