map实例练习1

题目:map例题:单词词频统计程序
输入大量单词,每个单词一行不超过20字符,没有空格。
按出现次数从多到少输出这些单词及其出现次数,出现次数相同的字典序靠前的在前面。

核心点:使用map的关键字的不可重复性进行存储单词和出现次数,另外使用set进行排序。
代码:

#include<iostream>
#include<string>
#include<map>
#include<set>
using namespace std;
struct words {  //定义键值对
	string word;
	int count;
};
struct rule
{//自定义排序规则
	bool operator()(const words& a1, const words& a2)const {
		if (a1.count != a2.count) return a1.count > a2.count;//先按出现次数多少排序
		else return a1.word < a2.word;//出现次数相同按字典序排序
	}
};
typedef map<string, int> MP;
int main()
{
	MP mp;
	string word;
	set<words, rule> st;//排序的关键
	while (cin >> word)
	{//利用map的关键字不可重复性,进行存储关键字和关键词出现次数
		pair<MP::iterator, bool> p = mp.insert(make_pair(word, 1));
		if (!p.second) mp[word]++;
	}
	MP::iterator i;
	for (i = mp.begin(); i != mp.end(); i++)
	{//排序
		words w;
		w.word = i->first;
		w.count = i->second;
		st.insert(w);
	}
	set<words, rule>::iterator p;
	for (p = st.begin(); p != st.end(); p++)
		cout <<p->word << ":" << p->count << endl;
	return 0;
}

实例结果:

记录于2024.11.15

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值