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 }

猜你喜欢

转载自www.cnblogs.com/jishuren/p/12242393.html