zoukankan      html  css  js  c++  java
  • [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 1328 Radar Installation (贪心)
    hdu 2037 今年暑假不AC (贪心)
    poj 2965 The Pilots Brothers' refrigerator (dfs)
    poj 1753 Flip Game (dfs)
    hdu 2838 Cow Sorting (树状数组)
    hdu 1058 Humble Numbers (DP)
    hdu 1069 Monkey and Banana (DP)
    hdu 1087 Super Jumping! Jumping! Jumping! (DP)
    必须知道的.NET FrameWork
    使用记事本+CSC编译程序
  • 原文地址:https://www.cnblogs.com/lightmonster/p/11648887.html
Copyright © 2011-2022 走看看