#include <iostream>
#include <map>
using namespace std;
//1.mulitmap和map的区别就是,multimap的key可以重复,而map不可以
//2.在查找时,find函数查找的是第一个key值相等的迭代器,不影响map,但是multi怎么查找所有的key值一样的元素的迭代器呢?
// (1)使用count(k)函数(求出键k出现次数)和find(k)函数(返回第一个拥有键k的迭代器)
// (2)使用lower_bound(k)函数和upper_bound(k),找到k的上下界(因为multimap中的key是有序的)--左闭右开
// (3)使用equal_range(k)函数,返回具有相同键值k的迭代器区间pair:[it1,it2),相当于一个上下界
int main(int argc, char** argv)
{
multimap<int, int> testMap;
testMap.insert(make_pair(1, 2));
testMap.insert(make_pair(1, 3));
testMap.insert(make_pair(1, 4));
testMap.insert(make_pair(2, 5));
testMap.insert(make_pair(3, 6));
//(1)使用第一种方法查找所以key为1的元素
int count = testMap.count(1);
auto it = testMap.find(1);
for (int i = 0; i < count; i++, it++)
{
cout << it->second << " ";
}
cout << endl;
//(2)使用第二种方法查找
auto it1 = testMap.lower_bound(1);
auto it2 = testMap.upper_bound(1);
for (; it1 != it2; it1++)
{
cout << it1->second << " ";
}
cout << endl;
//(3)使用第三种方法查找
auto it3 = testMap.equal_range(1);
for (auto it4 = it3.first; it4 != it3.second; it4++)
{
cout << it4->second << " ";
}
cout << endl;
return 0;
}
网友评论