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

原文链接: https://www.cnblogs.com/lightmonster/p/11648887.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    [C++]重复单词统计

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/303937

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月16日 上午1:15
下一篇 2023年2月16日 上午1:19

相关推荐