1、使用find和count:
count(k) 求出键k的出现次数
find(k) 返回第一个拥有键k的实例
multimap<int, int>::size_type cnt = testMap.count(searchItem);
multimap<int, int>::iterator iter = testMap.find(searchItem);
for(;cnt > 0; cnt--, iter++)
{
cout<<iter->first<<" "<<iter->second<<endl;
}
2、使用lower_bound与upper_bound:
lower_bound(k)返回迭代器指向不小于K的第一个元素
upper_bound(k)返回迭代器指向 大于k的第一个元素
multimap<int, int>::iterator iterBeg = testMap.lower_bound(searchItem);
multimap<int, int>::iterator iterEnd = testMap.upper_bound(searchItem);
for(;iterBeg != iterEnd;iterBeg++)
{
cout<<iterBeg->first<<"->"<<iterBeg->second<<endl;
}
3、使用equal_range:
equal_range(k):函数的返回值是一个pair,分别存放相同键k的迭代器区间。
auto ret = testMap.equal_range(searchItem);
auto it = ret.first;
while(it!=ret.second)
{
cout<<it->first<<"->"<<it->second<<endl;
++it;
}
4、程序测试:
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
multimap<int, int> testMap;
testMap.insert(make_pair(5,1));
testMap.insert(make_pair(5,2));
testMap.insert(make_pair(5,3));
testMap.insert(make_pair(5,4));
int searchItem = 5;
/*第一种方法*/
multimap<int, int>::size_type cnt = testMap.count(searchItem);
multimap<int, int>::iterator iter = testMap.find(searchItem);
for(;cnt > 0; cnt--, iter++)
{
cout<<iter->first<<"->"<<iter->second<<endl;
}
cout<<endl;
/*第二种方法*/
multimap<int, int>::iterator iterBeg = testMap.lower_bound(searchItem);
multimap<int, int>::iterator iterEnd = testMap.upper_bound(searchItem);
for(;iterBeg != iterEnd;iterBeg++)
{
cout<<iterBeg->first<<"->"<<iterBeg->second<<endl;
}
cout<<endl;
/*第三种方法*/
auto ret = testMap.equal_range(searchItem);
auto it = ret.first;
while(it!=ret.second)
{
cout<<it->first<<"->"<<it->second<<endl;
++it;
}
return 0;
}