「生活可以更简单, 欢迎来到我的开源世界」
  1. 定义QueryResult
  2. 定义TextQuery
  3. 编写main函数
  4. cmake文件
  5. file.txt文件
CppPrimer-第12章-文本查询程序
2018-06-20
」 「

定义QueryResult

//
// Created by modao on 2021/1/6.
//

#ifndef TEXT_QUERY_QUERYRESULT_H
#define TEXT_QUERY_QUERYRESULT_H

std::string make_plural(size_t ctr, const std::string &word, const std::string ending)
{
return (ctr == 1)? word: word + ending;
}
class QueryResult {
friend std::ostream &print(std::ostream&, const QueryResult&);
public:
using line_no = std::vector<std::string>::size_type;
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) { }
private:
std::string sought;
std::shared_ptr<std::set<line_no>> lines;
std::shared_ptr<std::vector<std::string>> file;
};

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

定义TextQuery

//
// Created by modao on 2021/1/6.
//

#ifndef TEXT_QUERY_TEXTQUERY_H
#define TEXT_QUERY_TEXTQUERY_H
#include "QueryResult.h"

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::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;
std::istringstream line(text);
std::string word;
while(line >> 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>> nodata(new std::set<line_no>);

auto loc = wm.find(sought);
if(loc == wm.end())
return QueryResult(sought, nodata, file);
else
return QueryResult(sought, loc->second, file);
}
#endif //TEXT_QUERY_TEXTQUERY_H

编写main函数

#include <fstream>
#include <iostream>
#include <vector>
#include <memory>
#include <map>
#include <set>
#include <string>
#include <sstream>

#include "TextQuery.h"

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() {
//必须使用绝对路径
std::ifstream file("E:\\clion_workspace\\Text_query\\file.txt");
runQueries(file);
return 0;
}

cmake文件

cmake_minimum_required(VERSION 3.12)
project(Text_query)

set(CMAKE_CXX_STANDARD 20)

add_executable(Text_query main.cpp TextQuery.h QueryResult.h)

file.txt文件

abc inad
sd faf
as
df
asfd
as
df
<⇧>