《c++ primer》12章习题:文本查询Demo

int main(){
	vector<string>text;
	text.push_back("The Meteorological Agency has called for caution against mudslides and flooding due to a record rainfall in Yamagata Prefecture, northern Japan");
	text.push_back("Weather officials forecast more heavy rain in the Tohoku region and Niigata Prefecture in northern Japan on Tuesday night");
	text.push_back("The officials say that 36 millimeters of rain fell in Uonuma City, Niigata Prefecture, in the one-hour period up to 7 p.m., Tuesday");
	map<string, set<size_t>> query;				//保存每个单词出现过的行号
	map<string, size_t> word_count;				//保存每个单词出现过的次数

	for (size_t st = 0; st < text.size(); ++st)
	{
		string s;
		istringstream iss(text[st]);
		
		while (iss >> s)			//遍历每个单词
		{
			query[s].insert(st);	//存行号和次数
			++word_count[s];
		}
	}
	for (auto i : query)		//打出来试验结果
	{
		cout << i.first <<" ";
		for (auto j : i.second)
		{
			cout << j <<" ";
		}
		cout << endl;
	}
	
	cout << "--------------------" << endl;
	for (auto i : word_count)
	{
		cout << i.first << " occurs" << i.second << " times" << endl;
	}
	cout << "--------------------" << endl;

	string test = "The";
	for (auto i : query[test])
	{
		cout << i << " " << text[i] << endl;
	}
	cout << "'The' occurs " << word_count[test] << " times" << endl;

	return 0;
}
©️2020 CSDN 皮肤主题: 1024 设计师:上身试试 返回首页