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


    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;
    }
    

      

  • 相关阅读:
    Redis(二) 扩展
    Redis(一)基础
    Java垃圾回收机制 入门
    freeregex-0.01 使用文档
    上传文件到阿里云linux服务器
    jQuery代码解释(基本语法)
    JQuery中使用FormData异步提交数据和提交文件
    jQuery获取data-*属性值
    jquery 中 $.map 的使用方法
    mysql创建表时反引号的作用
  • 原文地址:https://www.cnblogs.com/ladawn/p/8203789.html
Copyright © 2020-2023  润新知