文本查询程序,焦头烂额。
类文件名:TextQuer.hpp程序代码:
#include<iostream> #include<set> #include<map> #include<fstream> #include<string> class TextQuery{ public: typedef std::vector<std::string>::size_type line_to; void read_file(std::ifstream &is){ store_file(is); build_map(); } std::set<line_to>run_query(const std::string&)const; std::string text_line(line_no)const; private: void store_file(std::ifstream&); void build_map(); std::vector<std::string>lines_of_text; std::map<std::string,std::set<line_no> >word_map;}
类外定义成员函数:
TextQuer.cpp
程序代码:
#include<iostream> #include<set> #include<map> #include<fstream> #include<string> #include"TextQuery.hpp" using namespace std; void TextQuery::store_file(ifstream &is) { string s; while(getline(is,s)) lines_of_text.push_back(s); } void TextQuery::build_map(){ for(line_no ix=0;ix!=lines_of_text.size();++ix){ isringstream line(lines_of_text[ix]); string word; while(line>>word) word_map[word].insert(ix) ; } } std::set<line_to>TextQuery::run_query(const std::string&)const{ map<string,set<line_no> >::const_iterator loc=word_map.find(query_word); if(loc==word_map.end()) return set<line_no>(); else return loc->second; } 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"); }
主程序: main.cpp
程序代码:
#include<iostream> #include"TextQuery.hpp" #include<set> #include<map> #include<fstream> #include<string> using namespace std; void print_results(const set<TextQuery::line_no>)&locs,const string&sought,const TextQuery &file) { typedef set<TextQuery::line_no>line_nums; line_nums::size_type size=locs.size(); cout<<"\n"<<sought<<"occurs"<<size<<" "<<make_plural(size,"time","s"<<endl; line_nums::const_iterator it=locs.begin(); for(;it!=locs.end();++it){ cout<<"\t(line"<<(*it)+1<<" "<<file.text_line(*it)<<endl; } } int main(){ ifstream infile; if(argc<2||!open_file(infile,argv[1])){ cerr<<"NO input file"<<endl; return EXIT_FAILURE; } TextQuery tq; tq.read_file(infile); while(true){ cout<<"Enter word to loof for,orq to quit:"; string xx; cin>>xx; if(!cin||xx='q') break; set<TextQuery::line_no>locs=tq.run_query(xx); print_results(locs,xx,tq); } return 0; }
为什么运行不了TT 。。小错误我自己会检查,请前辈解答大错误。