• STL-map/multimap 简述


     1 #include <iostream>
     2 #include <cstdio>
     3 #include <map>
     4 
     5 using namespace std;
     6 
     7 
     8 int main()
     9 {
    10     // map && multimap
    11     // 键值映射容器,一对一,一对多
    12     // 都是红黑变体的平衡二叉树结构
    13 
    14     map<int,string> map1;
    15 
    16     // 插入元素
    17 
    18     // insert插入
    19     map1.insert(pair<int,string>(1,"ACM"));
    20     map1.insert(make_pair(2,"ACMER"));
    21     map1.insert(map<int,string>::value_type(3,"WIN"));
    22 
    23     // 重载运算符赋值
    24     map1[4]="I WIN";
    25     // 没有元素时,插入元素,有元素时,重新赋值
    26     // 比较方便的用法
    27 
    28     // 遍历也很方便,如果知道值的话
    29     for(int i=1;i<=4;++i)
    30     {
    31         cout<<map1[i]<<endl;
    32     }
    33 
    34     cout<<endl;
    35     // 当然,这才是正规的遍历方式
    36     for(map<int,string>::iterator it=map1.begin();it!=map1.end();++it)
    37     {
    38         cout<<(*it).first<<' '<<(*it).second<<endl;
    39     }
    40     cout<<endl;
    41 
    42 
    43     map<int,string>::iterator it=map1.find(2);
    44 
    45     map1.erase(it);
    46 
    47     for(map<int,string>::iterator it=map1.begin();it!=map1.end();++it)
    48     {
    49         cout<<(*it).first<<' '<<(*it).second<<endl;
    50     }
    51     cout<<endl;
    52 
    53     map1[2]="haha";
    54 
    55     map1[5]="heihei";
    56 
    57     for(map<int,string>::iterator it=map1.begin();it!=map1.end();++it)
    58     {
    59         cout<<(*it).first<<' '<<(*it).second<<endl;
    60     }
    61     cout<<endl;
    62 
    63     // 查找小于等于3的键
    64     it=map1.equal_range(3).first;
    65 
    66     map1.erase(it);
    67     for(map<int,string>::iterator it=map1.begin();it!=map1.end();++it)
    68     {
    69         cout<<(*it).first<<' '<<(*it).second<<endl;
    70     }
    71     cout<<endl;
    72 
    73     // 查找大于1的键
    74     it=map1.equal_range(1).second;
    75     map1.erase(it);
    76     for(map<int,string>::iterator it=map1.begin();it!=map1.end();++it)
    77     {
    78         cout<<(*it).first<<' '<<(*it).second<<endl;
    79     }
    80     cout<<endl;       
    81     
    82     
    83     // multimap 与 map类似
    84     // count,可以用来计算键有多少个值与之对应
    85 
    86     return 0;
    87 }
  • 相关阅读:
    利用树莓派把普通打印机变成网络打印机方法
    Python之datetime库
    CentOS7从默认/home中转移空间到根分区/
    更改Azure虚拟机账号密码
    创建一个托管磁盘的Windows定制镜像
    IO多路复用详解
    玩转redis
    EF Linq to Sql 多表left join查询并对结果group by分组之后进行count,max等处理
    免费,主流的在线办公/协作,会议,文档,调查,分享工具推荐(持续维护中)
    多sql查询count合并为一行
  • 原文地址:https://www.cnblogs.com/jishuren/p/12242393.html
Copyright © 2020-2023  润新知