1 #include<iostream>
2 #include<cstdlib>
3 using namespace std;
4 #include<map>
5
6
7 /*
8 3.9 map/multimap容器
9
10 3.9.1 map基本概念
11
12 简介:
13 map中所有元素都是pair
14 pair中第一个元素为key(键值),起到索引作用,第二个元素为value(实值)
15 所有元素都会根据元素的键值key自动排序
16
17 本质:
18 map/multimap属于关联式容器,底层结构是用二叉树实现。
19
20 优点:
21 可以根据key值快速找到value值
22
23 map和multimap区别:
24 map不允许容器中有重复key值元素
25 multimap允许容器中有重复key值元素
26
27
28 3.9.2 map构造和赋值
29
30 构造:
31 map<T1, T2> mp; //map默认构造函数:
32 map(const map &mp); //拷贝构造函数
33
34 赋值:
35 map& operator=(const map &mp); //重载等号操作符
36 */
37
38
39 void print_map(const map<int, int> & m)
40 {
41 for(map<int, int>::const_iterator cit=m.begin(); cit!=m.end(); cit++)
42 {
43 cout << "key=" << (*cit).first << " value=" << cit->second << endl;
44 }
45 cout << endl;
46 }
47
48
49 void test392()
50 {
51 map<int, int> m; //more构造
52
53 m.insert(pair<int, int> (1, 50)); //匿名对组
54 m.insert(pair<int, int> (2, 40));
55 m.insert(pair<int, int> (4, 20));
56 m.insert(pair<int, int> (5, 10));
57 m.insert(pair<int, int> (3, 30));
58
59 print_map(m); //插入数据时默认根据key自动实现升序排序
60
61 map<int, int> m2(m); //拷贝构造
62 print_map(m2);
63
64 map<int, int> m3;
65 m3 = m2; //赋值
66 print_map(m3);
67 }
68
69
70 int main()
71 {
72 test392();
73
74 system("pause");
75 return 0;
76 }
