2018.10.31——11.2關聯容器概述
阿新 • • 發佈:2018-12-18
11.8
#include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; int main(int argc, char * argv[]) { string word; vector<string> words; while(cin>>word) { if(find(words.begin(), words.end(), word) == words.end()) words.push_back(word); } for (auto &w : words) cout << w << " "; cout << endl; return 0; }
11.9
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <list> #include <map> #include <algorithm> using namespace std; int main(int argc, char *argv[]) { ifstream in(argv[1]); if (!in) { cerr << "無法開啟檔案" << endl; exit(1); } void tran(string &word) { for(int p = 0; p<word.size(); ++p); { if(word[p] < 'Z' && word[p] > 'A') word[p] -=( 'A' - 'a'); else if (word[p] = ',' || word[p] == '.' ) word[p] = word.erase(p,1); } } map<string, list<int>> word_lineno; string word; string line; int lineno; while (getline(in, line)) { lineno++; istringstream l_in(line); while(l_in >> word) { tran(word); word_lineno[word].push_back(lineno); } } for(const auto &w : word_lineno) { cout << word.lineno << "所在行 " ; for (const suto &i :w.lineno) cout << i << " "; cout << endl; } return 0; }
11.10
由於有序容器要求關鍵字型別必須支援比較操作<, 因此map<vector<int>::iterator,int> ml;
是可以的,vector的迭代器支援比較操作。而list元素不是連續儲存,其迭代器不支援比較操作
11.11 答案 首先用typedef定義與compareisbn相容的函式指標型別,然後用此型別宣告multiset即可
typedef bool (*pf) (const Sales_data &, const Sales_data &); multiset<Sales_data, pf> bookstore(compareisbn);