C++ multimap查找相同键的键值对方法

本文介绍了在C++中使用多重映射(multimap)进行数据查找的三种方法:使用count和find函数,使用lower_bound与upper_bound函数,以及使用equal_range函数。通过具体示例展示了如何实现这些查找操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值