标签:
/************************************************************************* * * Using the library: A Simple Test-Query Program * ************************************************************************/ #include<iostream> #include<vector> #include<string> #include<memory> //shared_ptr #include<map> #include<fstream> #include<set> #include<sstream> //istringstream using namespace std; typedef vector<string>::size_type line_no; class QueryResult { friend ostream& print(ostream&,const QueryResult&); public: QueryResult(string s,shared_ptr<set<line_no>> p,shared_ptr<vector<string>> f): sought(s),lines(p),file(f){} private: string sought; shared_ptr<set<line_no>> lines; shared_ptr<vector<string>> file; }; class TextQuery { public: TextQuery(ifstream&); QueryResult query(const string&) const; private: shared_ptr<vector<string>> file; map<string,shared_ptr<set<line_no>>> wm; }; TextQuery::TextQuery(ifstream &is):file(new vector<string>) { string lineText; while(getline(is,lineText)) { file->push_back(lineText); line_no n=file->size(); //current line number; istringstream line(lineText); string word; while(line>>word) { auto &lines=wm[word]; //lines is a share_ptr<set<line_no>> if(!lines) lines.reset(new set<line_no>); lines->insert(n); } } } QueryResult TextQuery::query(const string &sought) const { static shared_ptr<set<line_no>> nodata(new set<line_no>); auto loc=wm.find(sought); if(loc==wm.end()) return QueryResult(sought,nodata,file); else return QueryResult(sought,loc->second,file); } ostream &print(ostream &os,const QueryResult &qr) { os << qr.sought << " occurs " << qr.lines->size(); if(qr.lines->size()>1) os<<" times"<<endl; else os<<" time"<<endl; for(auto num : *qr.lines) os << "(line"<<num<<") "<< *(qr.file->begin()+num-1)<<endl; return os; } int main() { ifstream infile("1.txt"); //input a file,filename TextQuery tq(infile); while(true) { cout<< "enter the word to look for,or q to quit: "<<endl; string s; if(!(cin >> s) || s=="q") break; //input the search word print(cout,tq.query(s))<<endl; } return 0; }
标签:
原文地址:http://www.cnblogs.com/wxquare/p/4730499.html