C++文本查询程序 C++Primer练习12.28 使用vector,map,set容器保存来自文件的数据并生成查询结果

//.cpp文件
#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<iterator>
#include<algorithm>
```

using namespace std;
void Query(const string &word, int &numLine, map<int,string>&MapIntoStr,const vector<string>&LineString,const map<string,set<int>> &MapStoSet) 
{ //从文本进行单词查找,将查找的信息存在我们的输入变量中
	auto ret = MapStoSet.find(word);
	if (ret != MapStoSet.end())
	{
		auto setin = ret->second;
		numLine = setin.size();  //set里元素的个数就是出现的次数,即行数
		auto wz = setin.begin();
		string str;
		while (wz != setin.end())
		{
			str = LineString[*wz-1];
			MapIntoStr.insert(make_pair(*wz, str));
			++wz;
		}
	}
	else
		numLine = 0;
}
void print(const string &word, int numLine,const map<int,string>&MapIntoStr)
{
	cout <<word<< " occurs " << numLine << ((numLine> 1) ? " times" : " time") << endl;
	for (auto map_it = MapIntoStr.cbegin(); map_it != MapIntoStr.cend(); ++map_it)
	{
		cout << "(line " << map_it->first << ") " << map_it->second << endl;
	}
}
void getText(vector<string>&LineString, map<string, set<int>>&MapStoSet, ifstream& infile)
{//从外部文件中得到需要的信息
	string str;
	int i = 1;
	while(getline(infile,str))
	{
		LineString.push_back(str);
		istringstream istr(str);
		string word;
		set<int>setin = {i};
		while (istr >> word)
		{
			auto ret = MapStoSet.insert(make_pair(word, setin));//如果word已经存在,则什么都不做,如果没有,则用set(i)来构造对象
			if (!ret.second)    //如果单词已经出现在map中则将行号在原来的基础上插入行号
				(ret.first)->second.insert(i); 
		}
		++i;
	}
}
int main()
{
	ifstream infile("wordtext.txt");
	vector<string>LineString;//按行保存文本
	map<string, set<int>> MapStoSet;//保存每个单词出现的行号,且一行中出现多次则只记录一次
	string word;    //要查找的单词
	int numLine;    //单词出现的次数
	map<int, string> MapIntoStr;  //该单词出现的行以及该行所关联的文本
	cout << "Please Enter word to look for" << endl;
	cin >> word;                            //输入要查询的结果
	getText(LineString,MapStoSet,infile);  //从外部文件中得到需要的信息
	Query(word,numLine,MapIntoStr,LineString,MapStoSet);        //从文本进行单词查找,将查找的信息存在我们的输入变量中
	print(word, numLine, MapIntoStr);      //将查询信息输出
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值