C++Primer 文本查询程序再探
C++ Primer 5th 示例程序
拓展之前的简单文本查询程序,使得其可以进行一些逻辑查询,形如:
Query q= Query(“fiery”) & Query(“bird”) | ~Query (“wind”)
主要熟悉面向对象的解决方案
输入文本:
Alice Emma has long flowing red hair.
Her Daddy says when the wind blows
through her hair, it looks almost alive,
like a fiery bird in flight.
A beautiful fiery bird, he tells her,
magical but untamed.
“Daddy, shush, there is no such thing,”
she tells him, at the same time wanting
him to tell her more.
Shyly, she asks, “I mean, Daddy, is there?”
#include "pch.h"
#include <iostream>
#include <set>
#include <fstream>
#include <vector>
#include <map>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
using namespace std;
class QueryResult;
class TextQuery {
public:
TextQuery(ifstream& ifs);
QueryResult query(const string& s)const;
private:
shared_ptr<vector<string>> file;//保存文件的shared_ptr<vector>
map<string, shared_ptr<set<vector<string>::size_type>>> word_map;//单词和行号的映射 其中set也是一个shared_ptr
};
TextQuery::TextQuery(ifstream& ifs) :file(new vector<string>) {
string text;
while (getline(ifs, text)) {
//对文件的每一行
file->push_back(text);//存入vector中
unsigned n = file->size() - 1;//当前行号
string word;//一行中每个单词
text.erase(remove_if(text.begin(),text.end(),ispunct),text.end());//去掉当前行的标点 再逐词存入map
istringstream line_stream(text);//将每行文本绑定在istringstream
while (line_stream >> word) {
auto &lines = word_map[word];//lines获得一个行号set的shared_ptr
if (!lines) {
//如果单词不在map中 lines获得一个空指针--默认初始化的shared_ptr中保存着一个空指针
lines.reset(new set<vector<string>::size_type>);//必须为空指针lines分配一个新的set 不然解引用空指针导致灾难!
}
lines->insert(n);//将当前行号存入set
}
}
}
class QueryResult {
public:
friend ostream& print(ostream& os, const QueryResult &qr);
QueryResult(const string& s, shared_ptr<vector<string>> v, shared_ptr<set<vector<string>::size_type>> lines_set) :
file(v), lines(lines_set), sought(s) {
}
set<vector<string>::size_type>::iterator begin()const {
return lines->begin();
}