2018.10.24 ——10.3定製操作10.4再探迭代器
阿新 • • 發佈:2018-12-17
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