map , multimap , set , multiset的用法


先介绍一下pair的用法

pair<T1,T2>类型等价于:
struct {
	T1 first;
	T2 second;
};
例如 pair<int, double> a;
等价于 
struct {
	int first;
	double second;
}a;
a.first = 1;
a.second = 93.33;

然后来讲一下map和set,会发现,其实这四种都是利用二叉平衡树实现的(AVL),

在算一些数据的时候,如果需要进行大量查找,可以用数组+二分查找进行,但是如果同时需要进行大量的插入,删除,则需要使用到set和map等容器

multiset可以用insert, find, erase来进行logN的查找, 插入, 删除

mutiset<T> st;
st.insert
st.find
st.erase
st.lower_bound(12) <=
st.upper_bound(12) >

自定义排序规则的multiset

multiset<int, greater<int> >st; //跟sort(a,a+n,greater<int>())可以从大到小排序一样

struct Rule1 {
	bool operator()(const int& a, const int& b) {
		return (a % 10) < (b % 10);
	}
};
multiset<int, Rule1 >st;//按照个位数从小到大排

set和multiset的区别是容器里不能有重复的元素
set用法,
pair<set<int>::iterator,bool> result


总结:

map是关联容器,set是集合
multimap里的元素都是pair类型的
按照first排序,
map不能有重复key值,multimap可以有




给一个综合的例题

Description

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

Input

this
is
ok
this
plus
that
is
plus
plus


Output

plus 3
is 2
this 2
ok 1
that 1


#include <iostream>
#include <set>
#include <map>
#include <string>
using namespace std;
/*
map例题:单词词频统计程序
输入大量单词,每个单词,一行,不超过20字符,没有空 格。 按出现次数从多到少输出这些单词及其出现次数。 出现次数相同的,字典序靠前的在前面
INPUT:
this
is
ok
this
plus
that
is
plus
plus

输出样例:
plus 3
is 2
this 2
ok 1
that 1
*/
struct Word {
	int times;
	string wd;
};
struct Rule {  //按照时间从大到小,时间相同则按照名字顺序来
	bool operator()(const Word & w1, const Word & w2) {
		if (w1.times != w2.times)
			return w1.times > w2.times;
		else
			return w1.wd < w2.wd;
	}
};
/*
思路:先对输入的数据进行统计,用map得到每个单词对应的次数
然后用set对单词的次数和字母表顺序进行排序
http://www.icourse163.org/learn/PKU-1001553023?tid=1001762001#/learn/content
*/
int main()
{
	string str;
	set<Word, Rule> st;
	map<string, int>mp;
	while (cin >> str)
		mp[str]++;
	for (map<string, int>::iterator it = mp.begin(); it != mp.end(); it++)
	{
		Word tmp;
		tmp.wd = it->first;
		tmp.times = it->second;
		st.insert(tmp);//插入进行后直接按照自定义的Rule排序
	}
	for (set<Word, Rule>::iterator it = st.begin(); it != st.end(); it++)
	{
		cout << it->wd << " " << it->times << endl;
	}
	return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值