码迷,mamicode.com
首页 > 其他好文 > 详细

A simple Test-Query Program

时间:2015-08-14 17:01:22      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:

/*************************************************************************
 *
 *  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;
}

 

A simple Test-Query Program

标签:

原文地址:http://www.cnblogs.com/wxquare/p/4730499.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!