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; }
原文链接: https://www.cnblogs.com/ladawn/p/8203789.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/267173
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!