multimap的使用方法

multimap主要用于一个key值对应多个value的情况,比如一个人可以有很多个电话号码,其他的使用都还简单,主要记录一下怎么遍历:

/*multimap的遍历方法,主要利用multimap中同一个key对应的value值连续存储这一特性*/
#include<iostream>
#include<string>
#include<map>
#include<set>
using namespace std;
typedef multimap<string, int>::iterator iter;

int main()
{
	multimap<string, int> mul_map;
	set<string> name;				//用set存储所有不重复的人名
	mul_map.insert(make_pair("tim", 5));
	mul_map.insert(make_pair("tim", 50));
	mul_map.insert(make_pair("tim", 500));
	mul_map.insert(make_pair("jack", 15));
	mul_map.insert(make_pair("jack", 44));
	mul_map.insert(make_pair("hello", 123));
	for (auto x : mul_map)
		name.insert(x.first);
	/********方法一*********/
	iter m;
	for (auto x : name)
	{
		m = mul_map.find(x);
		cout << x << ": ";
		for (int i = 0; i < mul_map.count(x); i++, m++)
			cout << m->second << " ";
		cout << endl;
	}
	/********方法二*********/
	iter beg, end;
	for (auto x : name)
	{
		beg = mul_map.lower_bound(x);
		end = mul_map.upper_bound(x);
		cout << x << ": ";
		for (iter i = beg; i != end; i++)
			cout << i->second << " ";
		cout << endl;
	}
	/********方法三*********/
	for (auto x : name)
	{
		beg = mul_map.equal_range(x).first;// 返回一个迭代器的pair对象,first成员等价于lower_bound(key),second成员等价于upper_bound(key)
		end = mul_map.equal_range(x).second;
		cout << x << ": ";
		for (iter i = beg; i != end; i++)
			cout << i->second << " ";
		cout << endl;
	}
	return 0;
}


posted @ 2016-12-17 13:42  seasonal  阅读(557)  评论(0编辑  收藏  举报