这将实现一个简单的文本查询程序,使用到shared_ptr智能指针,map、set、vector等容器。适合学习
#include<iostream>
#include<sstream>
#include<map>
#include<set>
#include<vector>
#include<memory>
#include<string>
#include<fstream>
using namespace std;
class QueryResult;
class TextQuery{
public:
using line_no = vector<string>::size_type;
TextQuery(ifstream &infile);
QueryResult query(const string &q_text) const;
private:
shared_ptr<vector<string>> file;
map<string, shared_ptr<set<line_no>>> wm;
};
class QueryResult
{
friend ostream& print(ostream& ,const QueryResult &);
public:
using line_no = vector<string>::size_type;
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;
};
TextQuery::TextQuery(ifstream &infile):file(new vector<string>)
{
string text;
int n = 0;
while (getline(infile, text)) {
file->push_back(text);
cout<<text<<endl;
istringstream line(text);
string word;
while (line >> word){
auto &lines = wm[word];
if (! lines)
lines.reset(new set<line_no>);
lines->insert(n);
}
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()<<" "
<< " times"<<endl;
for (auto num : *qr.lines)
os << "\t(line "<<num + 1<<")"<< *(qr.file->begin() + num)<<endl;
return os;
}
void runQueries(ifstream &infile)
{
TextQuery tq(infile);
while (1){
cout<<"enter a word to look for, or q to quit: ";
string s;
if ( !(cin >> s) || s == "q") break;
print(cout, tq.query(s)) << endl;
}
}
int main()
{
ifstream infile;
infile.open("D:\\words.txt");
if (infile.is_open())
runQueries(infile);
else
cout<<"nonono"<<endl;
return 0;
}