10.22
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
using namespace std::placeholders;
void output_words(const string &s)
{
for(auto iter = s.begin(); iter != s.end() ; ++iter)
cout << *iter << " ";
cout << endl;
}
bool compared6(const string &s, vector<string>::size_type sz)
{
return s.size() <= sz;
}
int main(int argc, char *argv[])
{
ifstream in(argv[1]);
if (!in)
{
cerr << "无法打开文件" << endl;
exit(1);
}
vector<string> words;
string word;
while(in >> word)
words.push_back(word);
output_words(words);
auto bz = count_if(words.begin(), words.end(), bind(compared6, _1, 6));
cout <<bc << endl;
return 0;
}
答案
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
#include "make_plural.h"
using namespace std;
using namespace std::placeholders;
inline void output_words(const vector<string> &s)
{
for(auto iter = s.begin(); iter != s.end() ; ++iter)
cout << *iter << " ";
cout << endl;
}
bool compared6(const string &s, string::size_type sz)
{
return s.size() <= sz;
}
void biggies(vector<string> &words, vector<string>::size_type sz)
{
output_words(words);
auto bc = count_if(words.begin(0, words.end(), bind(compared6, _1, sz));
cout << bc << endl;
}
int main(int argc, char *argv[])
{
ifstream in(argv[1]);
if (!in)
{
cerr << "无法打开文件" << endl;
exit(1);
}
vector<string> words;
string word;
while(in >> word)
words.push_back(word);
biggies(words, 6);
return 0;
}
10.23
答案
bind是可变参数。它接受的第一个参数是一个可调用对象,即实际工作函数A,返回供算法使用的新的可调用函数B。若A接受x个参数,则bind的参数个数应该是x+1,即除了A外,其他参数应一一对应A所接受的参数。这些参数中有一部分来自于B(_n),另外来自于所处函数的局部变量。
10.24