• [C++]重复单词统计


    //textquery.h
    #pragma once
    #ifndef TEXTQUERY_H_
    #define TEXTQUERY_H_
    #include <vector>
    #include <memory>
    #include <map>
    #include <set>
    #include <string>
    
    #include <iostream>
    #include <fstream>
    #include <sstream>
    using namespace std;
    class QueryResult;
    class TextQuery {
    public:
        using line_no = std::vector<std::string>::size_type;
        TextQuery(std::ifstream&);
        QueryResult query(const std::string&) const;
    private:
        std::shared_ptr<std::vector<std::string>> file;
        std::map<std::string, std::shared_ptr<std::set<line_no>>> wm;
    };
    #endif // !TEXTQUERY_H_
    //textquery.cpp
    #include "pch.h"
    #include "textquery.h"
    #include "queryresult.h"
    TextQuery::TextQuery(std::ifstream &is) :file(new std::vector<std::string>) {
        std::string text;
        while (getline(is,text))
        {
            file->push_back(text);
            int n = file->size() - 1;
            istringstream line(text);
            string word;
            while (line>>word)
            {
                auto& lines = wm[word];
                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);
    }
    //queryresult.h
    #pragma once
    #ifndef QUERYRESULT_H_
    #define QUERYRESULT_H_
    #include "textquery.h"
    class QueryResult {
        friend std::ostream& print(std::ostream&, const QueryResult&);
    public:
        QueryResult(string s, shared_ptr<set<TextQuery::line_no>> p, shared_ptr<vector<string>> f) :sought(s), lines(p), file(f) {}
    private:
        string sought;
        shared_ptr<set< TextQuery::line_no>> lines;
        shared_ptr<vector<string>> file;
    };
    
    #endif // !QUERYRESULT_H_

    TextQuery类用来读取文本并提取每个单词出现的行并保存该行至容器map中

    QueryResult类用来查询单词是否出现并打印结果。

    使用shared_ptr来避免TextQuery对象先于QueryResult销毁,导致程序无法正常执行。

  • 相关阅读:
    POJ 2485 Highways &amp;&amp; HDU1102(20/200)
    easyui 后台框架搭建
    启动第二个Activity
    Apache配置基于域名的虚拟主机
    POJ_1679_The Unique MST(次小生成树模板)
    MySQL学习笔记
    数据库学习之简单的SQL语句
    HDU-4643-GSM(DFS)
    Android Studio VS Eclipse (还在用Eclipse?你OUT了!)
    使用国内镜像源来加速python pypi包的安装
  • 原文地址:https://www.cnblogs.com/lightmonster/p/11648887.html
Copyright © 2020-2023  润新知