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

使用标准库:文本查询程序

时间:2020-03-15 13:36:32      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:文本   ring   标准   ack   stream   begin   oda   get   res   

使用标准库:文本查询程序

class QueryResult
{
friend  std::ostream& print(std::ostream&,cost QueryResult&);
public:
    Queryresult(std::string s,
                std::shared_ptr<std::set<line_no>> p,
                std::shared_ptr<std::vector<std::string>>f):
                sought(s),lines(p),file(f){ }
private:
    std::string sought;     //查询单词
    std::shared_ptr<std::set<line_no>> lines;       // 出现的行号
    std::shared_ptr<std::vector<std::string>> file;     // 输入文件

};

class TextQuery{
pulic:
    using line_no = std::vector<std::string>::size_type;
    TextQuery(std::ifstream&);
    QueryResult query(const std::strng&) const;
private:
    std::shared_ptr<std::vector<std::string>> file;
    std::map<std::string,std::shared_ptr<std::set<line_no>>> wm;
};

TextQuery::TextQuery(iftream& is):file(new vector<string>)
{
    string text;
    while(getline(is,text))     //  对文件中的每一行
    {
        file->push_back(text);  // 保存文本
        int n = file->size() - 1;   // 保存当前行号
        istringstream line(text);   // 将行文本拆解为单词
        string word;
        while(line >> word)
        {
            // 如果这个单词不在vm中,以下标在vm中添加一项
            auto& lines = wm[word];     // lines 是一个shared_ptr
            if(!lines)  // 如果第一次遇到这个单词,此指针为空
                lines.reset(new set<line_no>);
            lines->insert(n);   // 将此行号插入到 set 中
        }       
    }
}

QueryResult TextQuery::query(const string& sought) const
{
    static shared_ptr<set<line_np>> 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()<<" "<<make_plural(qr.lines->size(),"times","s")<<endl;
    for(auto num : *qr.lines)
        os <<"\t(line"<<num+1<<")"<<*(qr.file->begin()+num)<<endl;
    
    return os;
}

使用标准库:文本查询程序

标签:文本   ring   标准   ack   stream   begin   oda   get   res   

原文地址:https://www.cnblogs.com/xiaojianliu/p/12496833.html

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