zoukankan      html  css  js  c++  java
  • C++ multimap容器访问同一键值元素的不同方法

    multimap是一种多元map容器,允许一个键对应多个值。

    本文介绍了 multimap访问同一键值元素的三种不同方法,详细看下面代码:

     1 typedef multimap<string,int>::size_type mstype;
     2 typedef multimap<string,int>::iterator mulit;
     3 multimap<string,int> mulmap;
     4 //插入元素
     5 mulmap.insert(make_pair("abc",2));
     6 mulmap.insert(make_pair("abc",3));
     7 mulmap.insert(make_pair("bcd",5));
     8 mulmap.insert(make_pair("bcd",7));
     9 
    10 for(mulit mt=mulmap.begin();mt!=mulmap.end();mt++){
    11     cout<<mt->first<<" "<<mt->second<<endl;
    12 }
    13 /*方式1:最麻烦的方式:
    14 (1)通过iter=find()找到某个键对应元素的迭代器,如果该键值对应多个值,则返回指向第一个元素的迭代器。
    15 (2)通过cn=count()返回对应键元素的个数
    16 (3)以迭代器iter为起始位置,遍历cn次
    17 */
    18 cout<<"find count 方式:"<<endl;
    19 mulit mb=mulmap.find("abc");
    20 mstype mt=mulmap.count("abc");
    21 for(mstype tt=0;tt<mt;tt++,mb++){
    22     cout<<mb->first<<" "<<mb->second<<endl;
    23 }
    24 /*方式2:upper_bound和lower_bound方式
    25 通过lower_bound和upper_bound获取指向一个键对应元素的迭代器范围,其中
    26 lower_bound返回指向键对应的第一个元素的迭代器位置
    27 upper_bound返回指向这个键对应的最后一个元素的下一个位置的迭代器
    28 */
    29 cout<<"upper_bound lower_bound 方式:"<<endl;
    30 mulit lower=mulmap.lower_bound("bcd");
    31 mulit upper=mulmap.upper_bound("bcd");
    32 for(mulit tm=lower;tm!=upper;tm++){
    33     cout<<mb->first<<" "<<mb->second<<endl;
    34 }
    35 /*方式3:直接用equal_range方法返回用pair封装的两个迭代器,两个迭代器类似于lower_bound和upper_bound返回的结果
    36 */
    37 typedef pair<mulit,mulit> pmulit;
    38 pmulit pl=mulmap.equal_range("bcd");
    39 for(mulit tm=pl.first;tm!=pl.second;tm++){
    40     cout<<mb->first<<" "<<mb->second<<endl;
    41 }

    因此推荐用后两种方式去获取同一键值的所有元素。

  • 相关阅读:
    shell编程-基础
    磁盘管理-下部
    磁盘管理-中部
    磁盘管理-上部
    用户的管理
    docker之阿里云centos 7.x 启动容器报错处理办法
    IDEA之整合SVN遇到的坑(一)
    springboot之通过idea打jar包并运行
    SpringBoot整合定时任务和异步任务处理
    Microsoft SQL Server 2012安装说明
  • 原文地址:https://www.cnblogs.com/jfcspring/p/3267938.html
Copyright © 2011-2022 走看看