本题目对应于 C++primer(第四版)中 第十章的文本查询类(TextQuery)
用到的知识有:
顺序容器 vector
关联容器 set,map
标准输入输出流,文件流,字符串流
//写一个文件 从文件中读单词 输出单词的次数和所在的行数 //... #include <iostream> #include <fstream> #include <sstream> #include <string> #include <set> #include <vector> #include <map> class TextQuery { public: typedef std::vector<std::string>::size_type line_no; //read the file void read_file(std::ifstream &is){ store_file(is); build_map(); } //query the file return the times every word appears std::set<line_no> run_query(const std::string&) const; //return the line-number of the word std::string text_line(line_no) const; private: void store_file(std::ifstream &is); void build_map(); std::vector<std::string> lines_of_text; std::map<std::string, std::set<line_no>> word_map; }; void TextQuery::store_file(std::ifstream &is){ std::string textline; while(std::getline(is, textline)){ lines_of_text.push_back(textline); } } void TextQuery::build_map(){ for(line_no line_num = 0; line_num != lines_of_text.size(); ++line_num){ std::istringstream line(lines_of_text[line_num]); std::string word; while(line >> word){ word_map[word].insert(line_num); } } } //read to get times of every word appears std::set<TextQuery::line_no> TextQuery::run_query(const std::string& query_word) const{ std::map<std::string, std::set<line_no>>::const_iterator loc = word_map.find(query_word); if(loc == word_map.end()){ return std::set<line_no>(); } else{ return loc->second; } } //read to get the line-number of the word std::string TextQuery::text_line(line_no line) const{ if(line < lines_of_text.size()){ return lines_of_text[line]; throw std::out_of_range("line number out of range"); } }; std::string make_plural(size_t ctr, const std::string& word, const std::string& ending){ return (ctr == 1) ? word : word + ending; } void print_results(const std::set<TextQuery::line_no>& locs, const std::string& sought, const TextQuery& file){ typedef std::set<TextQuery::line_no> line_nums; line_nums::size_type size = locs.size(); std::cout<< " " << sought << "occurs " << size << " " << make_plural(size, "time", "s") << std::endl; line_nums::const_iterator it = locs.begin(); for(; it != locs.end(); ++it){ std::cout << " (line" << (*it) + 1 << ")" <<file.text_line(*it) << std::endl; } } int main(){ std::ifstream infile("F:\input.txt"); TextQuery tq; tq.read_file(infile); while(true){ std::cout << "enter word to look for, or q to quit: "; std::string s; std::cin >> s; if(!std::cin || s == "q") break; // get the set of line numbers on which this word appears std::set<TextQuery::line_no> locs = tq.run_query(s); print_results(locs, s, tq); } return 0; }