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销毁,导致程序无法正常执行。

  • 相关阅读:
    【原】相煎何太急——input的blur事件与button的click事件
    【原】jQuery与CSS自动生成验证码
    【转】HTML转义字符大全
    【原】来自于一位前端“布道者”的建议
    【原】如何在jQuery中实现闭包
    【转】Web前端研发工程师编程能力飞升之路
    【原】git如何删除本地和远程的仓库
    H5不同样式新闻垂直滚动效果
    mui防止软键盘弹起方法
    js显示对象所有属性和方法的函数
  • 原文地址:https://www.cnblogs.com/lightmonster/p/11648887.html
Copyright © 2011-2022 走看看