首页 > 其他 > 详细

A simple Test-Query Program

时间:2015-08-14 16:59:25      阅读:147      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!