12.3.1

QueryResult.h

#pragma once
#include<memory>
#include<set>
#include<string>
#include<vector>
class QueryResult {
    using line_no = std::vector<std::string>::size_type;
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){}

    friend std::ostream &print(std::ostream& os, const QueryResult&qr);
private:
    std::string sought;
    std::shared_ptr<std::set<line_no> > lines;
    std::shared_ptr<std::vector<std::string> > file;

};

TextQuery.h

#pragma once
#include<fstream>
#include<string>
#include<sstream>
#include<vector>
#include<memory>
#include<map>
#include<set>

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;

};

TextQuery.cpp

#include"TextQuery.h"
#include"QueryResult.h"
TextQuery::TextQuery(std::ifstream& infile) :file(new std::vector<std::string>)
{
    std::string line;
    while (getline(infile, line)) {
        file->push_back(line);
        int n = file->size();
        std::istringstream aline(line);
        std::string word;
        while (aline >> word) {
            auto &lines = wm[word];
            if (!lines)
                lines.reset(new std::set<line_no>);
            lines->insert(n);
        }


    }

}
QueryResult TextQuery::query(const std::string&sought) const {
    static std::shared_ptr<std::set<line_no>> nodate(new std::set<line_no>);
    auto loc = wm.find(sought);
    if (loc == wm.end()) {
        return QueryResult(sought, nodate, file);
    }
    else
    {
        return QueryResult(sought, loc->second, file);
    }
}

Main

#include"TextQuery.h"
#include"QueryResult.h"
#include<iostream>

std::ostream &print(std::ostream& os, const QueryResult&qr) {
    os << qr.sought << " occurs " << qr.lines->size() << (qr.lines->size() > 1 ? " times" : " time") << std::endl;
    for (auto num : *qr.lines) {
        os << "\t(line " << num << ") "<< *(qr.file->begin() + num - 1) << std::endl;
    }
    return os;
}

void runQueries(std::ifstream &infile) {

    TextQuery tq(infile);
    while (true) {
        std::cout << "enter word to look for,or q to quit: ";
        std::string s;
        if (!(std::cin >> s) || s == "q")
            break;
        print(std::cout, tq.query(s)) << std::endl;

    }

}


int main(){

    runQueries(std::ifstream("TXT.txt"));
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值