C++Primer 12.3中的文本查询设计

只定义了一个类,代码感觉要精简一点
类定义:CTextQuery.h
#pragma once
#include <string>
#include <vector>
#include <map>
#include <set>
#include <sstream>
#include <fstream>
#include <iostream>

class TextQuery {
public:
	TextQuery(std::ifstream& infile);
	void seachAndPrint(std::string& word);//查询打印结果
private:
	//保存每一行的vector,行号从0开始
	std::vector<std::string> vtext{};
	//key:单词  value:出现的行的集合
	std::map<std::string, std::set<size_t>> word_line{};
	//查询:map.size()为出现的次数,map.first为每一个行号,second为对应行的文本
	std::map<size_t, std::string> sarchWord(std::string& word);
};

inline TextQuery::TextQuery(std::ifstream& infile)
{
	std::string line;
	size_t sz = 0;
	while (getline(infile, line))
	{
		vtext.push_back(line);//读取每一行保存到vector
		std::istringstream is_line(line);
		std::string word;
		while (is_line >> word)
		{
			word_line[word].insert(sz);//保存word到set<size_t>的map
		}
		++sz;
	}

}
inline std::map<size_t, std::string> TextQuery:: sarchWord(std::string& word)
{
	std::map<size_t, std::string> ret{};
	auto iter = word_line.find(word);
	if (iter != word_line.end())
	{
		auto it = vtext.begin();
		for (auto &i : iter->second)//提取每一个行号
		{
			ret.insert({ i,*(it +i) });//插入元素
		}
	}
	return ret;
}
inline void TextQuery::seachAndPrint(std::string& word)
{
	auto result =sarchWord(word);
	std::cout << word << "一共出现" << result.size() << "次" << std::endl;
	if (result.size() != 0)
	{
		for (auto &w : result)
		{
			std::cout << "第 " << w.first + 1 << " 行:" << w.second << std::endl;
		}
	}
}



main.cpp
#include "stdafx.h"
#include "CTextQuery.h"
using namespace std;
int main()
{
	ifstream infile("input.txt");
	TextQuery mquery(infile);
	string word;
	cin >> word;
	mquery.seachAndPrint(word);

	getchar();
	getchar();
    return 0;
}


阅读更多
文章标签: c++ c++ prime
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭