C++Primer 文本查询程序再探

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();
	}
	
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值