//有几个函数是前面几章写过的,但是本章没贴出来 //比如 open_file(),make_plural(),我把open_fie()改成infile.open()了,已经g++测试通过 #include #include #include #include #include #include #include using namespace std; class TextQuery { public: typedef vector::size_type line_no; void read_file(ifstream &is){ store_file(is); build_map(); } set run_query(const string&) const; string text_line(line_no) const; line_no size() const { return lines_of_text.size(); } private: void store_file(ifstream&); void build_map(); vector lines_of_text; map > word_map; }; void TextQuery::store_file(ifstream &is) { string line; while(getline(is,line)) lines_of_text.push_back(line); } void TextQuery::build_map() { for(line_no iline = 0;iline != lines_of_text.size();++iline){ stringstream istr(lines_of_text[iline]); string word; while(istr >> word) word_map[word].insert(iline); } } set TextQuery::run_query(const string &word) const { map >::const_iterator iter; if((iter = word_map.find(word)) != word_map.end()) return iter -> second; else{ set tempset; return tempset; } } string TextQuery::text_line(line_no iline) const { return lines_of_text[iline]; } string make_plural(int size, const string &word, const string &sfx ){ if(size > 1) return word + sfx; else return word; } void print_results(const set& locs, const string& sought, const TextQuery &file) { // if the word was found, then print count and all occurrences typedef set line_nums; line_nums::size_type size = locs.size(); cout << "\n" << sought << " occurs " << size << " " << make_plural(size, "time", "s") << endl; // print each line in which the word appeared line_nums::const_iterator it = locs.begin(); for ( ; it != locs.end(); ++it) { cout << "\t(line " // don't confound user with text lines starting at 0 << (*it) + 1 << ") " << file.text_line(*it) << endl; } } int main(int argc, char **argv) { // open the file from which user will query words ifstream infile; if(argc < 2) { cerr << "./a " << endl; return EXIT_FAILURE; } infile.open(argv[1]); if (!infile) { cerr << "cannot open file!" << endl; return EXIT_FAILURE; } TextQuery tq; tq.read_file(infile); // builds query map // iterate with the user: prompt for a word to find and print results // loop indefinitely; the loop exit is inside the while while (true) { cout << "enter word to look for, or q to quit: "; string s; cin >> s; // stop if hit eof on input or a 'q'is entered if (!cin || s == "q") break; // get the set of line numbers on which this word appears set locs = tq.run_query(s); // print count and all occurrences, if any print_results(locs, s, tq); } return 0; }
好像是第十章的那个查询系统不完整,后面有一张吧那个查询系统完整描述了一遍的当时我也是敲那个程序敲了半天是个错的
这个你还要求别人有一本C++ primer 而且是 第四版 还而且是 上。题都懒得打啊你? 唉~