需求介绍
假如有这样的需求:
处理一个英文文本(简单处理为无标点),用户输入一个单词:如you,
程序执行,显示you在文本文件中出现的次数,以及其所在行的内容。如果该单词在一行中出现多次,则此行只显示一次即可。查询结果按行号升序输出各行内容。
解决思路
利用C++实现这样一个简单的文本查询需求十分简单。
编写两个类
1)TextQuery
2)QueryResult
所用数据结构:
- 使用vector< string > 保存文本文件
- 用istringstream将每行分解为单词
- 使用set来保存单词在文本中出现的所有行号
- 使用map将每个单词与其出现所有行号的set进行映射
- 使用shared_ptr 进行对象内存共享
具体实现代码:
类定义 & 成员函数
最好分开文件实现(在此偷懒都写在一个头文件中)
#ifndef _TEXTQUERY_H
#define _TEXTQUERY_H
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <map>
#include <set>
#include <memory>
using std::shared_ptr;
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
using namespace std;
class QueryResult;
class TextQuery {
public:
using line_no = std::