1、multimap的概念
multimap和map的唯一差别就是map中的key必须是唯一的,而multimap中的key是可以重复的,其底层结构及方法接口与map完全相同。
2、multimap的基本操作
使用map时,必须包含
#include<iostream>
#include<map>
#include<stdlib.h>
using namespace std;
void TestMultimap1()
{
map<int, int> map1;
map1.insert(pair<int, int>(1, 10));
map1.insert(make_pair(2, 20));
map1.insert(make_pair(3, 30));
map1.insert(make_pair(4, 40));
map1.insert(make_pair(5, 50));
cout << "map中的元素的个数为:" << map1.size() << endl;
//尝试插入key值相同,但是value不同的元素
map1.insert(make_pair(2, 2));
cout << "插入key值相同,但是value不同的元素后,map中的元素的个数为:" << map1.size() << endl;
cout << "multimap中的元素有:" << endl;
multimap<int, int> multi1;
for (int i = 0; i < 5; i++)
{
multi1.insert(make_pair(i, i));
}
multi1.insert(make_pair(1, 10));
multi1.insert(make_pair(2, 20));
multi1.insert(make_pair(2, 200));
multimap<int, int>::iterator iter = multi1.begin();
while (iter != multi1.end())
{
cout << iter->first << "--->" << iter->second << endl;
++iter;
}
cout << "在multimap中key为2的元素个数:" << multi1.count(2) << endl;
iter = multi1.lower_bound(2);
cout << "multi1.lower_bound(2):" << iter->first << "--->" << iter->second << endl;
iter = multi1.upper_bound(2);
cout << "multi1.upper_bound(2):" << iter->first << "--->" << iter->second << endl;
typedef multimap<int, int>::iterator Iter;
pair<Iter, Iter> ret = multi1.equal_range(2);
cout << (ret.first)->first <<"--->" << (ret.first)->second << endl;
for (auto it = ret.first; it != ret.second; it++)
{
cout << it->first << "--->" << it->second << endl;
}
cout << (ret.second)->first << "--->" << (ret.second)->second << endl;
}
int main()
{
TestMultimap1();
system("pause");
return 0;
}
运行结果为: