C++从一个文件中统计所有出现过的单词,并按次数从大到小输出

#include <iostream>
#include <string>
#include <fstream>
#include <map>
#include <algorithm>

using namespace std;

int main()
{
	ifstream input;
	input.open("word.txt");
	string eachline;
	map<string, int> mapA; //第一个存单词,第二个存单词出现的次数;

	while (getline(input, eachline))
	{
		string::size_type start = 0;
		string::size_type end = eachline.find_first_of(" ");
		while (end != string::npos) //npos就是这一行到头啦;
		{
			string content = eachline.substr(start, end - start);
			map<string, int>::iterator it = mapA.find(content);
			if (it == mapA.end())
			{
				mapA.insert(pair<string, int>(content, 1));//赋值的时候只接受pair类型;
			} else
			{
				++it->second;

			}
			start = end + 1;
			end = eachline.find_first_of(" ", start);
		}

	}
	multimap<int, string, greater<int> > mapB;

	for (map<string, int>::iterator it1 = mapA.begin(); it1 != mapA.end();++it1)
	{
		mapB.insert(pair<int, string>(it1->second, it1->first));
	}

	for (map<int, string>::iterator it2 = mapB.begin(); it2 != mapB.end();++it2)
	{
//		if ((it2->first) > 1)
			cout << it2->second << "单词出现的次数是" << it2->first << endl;
	}

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值