1 #include<iostream>
2 #include<cstdlib>
3 using namespace std;
4 #include<map>
5
6
7 /*
8 3.9.5 map查找和统计
9
10 find(key); //查找key是否存在,若存在,返回该键的元素的迭代器;若不存在,返回set.end();
11 count(key); //统计key的元素个数
12
13 3.9.6 map排序
14
15 map容器默认排序规则为 按照key值进行 从小到大排序
16 利用仿函数,可以改变排序规则
17 */
18
19
20 void print_map(const map<int, int> & m)
21 {
22 for(map<int, int>::const_iterator cit=m.begin(); cit!=m.end(); cit++)
23 {
24 cout << "key=" << (*cit).first << " value=" << cit->second << endl;
25 }
26 cout << endl;
27 }
28
29
30 void test395()
31 {
32 map<int, int> m;
33 m.insert(make_pair(1, 10));
34 m.insert(make_pair(2, 20));
35 m.insert(make_pair(3, 30));
36 print_map(m);
37
38 map<int, int>::iterator pos = m.find(3);
39 if(pos != m.end())
40 {
41 cout << "找到元素key=" << pos->first << " value=" << (*pos).second << endl;
42 }
43 else
44 {
45 cout << "未找到元素" << endl;
46 }
47
48 //map容器不允许插入重复key元素,即必须保持key唯一性
49 int num = m.count(3);
50 cout << "num of 3 in m:" << num << endl; //非0即1
51
52 multimap<int, int> mm; //multimap允许key重复
53 mm.insert(make_pair(2, 20));
54 mm.insert(make_pair(2, 200));
55 mm.insert(make_pair(4, 4));
56 mm.insert(make_pair(1, 10));
57 mm.insert(make_pair(3, 3));
58 for(multimap<int, int>::iterator it=mm.begin(); it!=mm.end(); it++)
59 {
60 cout << "key=" << (*it).first << " value=" << it->second << endl;
61 }
62 }
63
64
65 class MyCompare
66 {
67 public:
68 bool operator()(int num1, int num2)
69 {
70 //降序:令 前一数 > 后一数
71 return num1 > num2;
72 }
73 };
74
75
76 void test396()
77 {
78 map<int, int> m;
79 m.insert(make_pair(1, 10));
80 m.insert(make_pair(5, 50));
81 m.insert(make_pair(4, 40));
82 m.insert(make_pair(2, 20));
83 m.insert(make_pair(3, 30));
84 print_map(m);
85
86 map<int, int, MyCompare> m2; //利用仿函数指定排序规则实现降序
87 m2.insert(make_pair(1, 10));
88 m2.insert(make_pair(5, 50));
89 m2.insert(make_pair(4, 40));
90 m2.insert(make_pair(2, 20));
91 m2.insert(make_pair(3, 30));
92 for(map<int, int, MyCompare>::iterator it=m2.begin(); it!=m2.end(); it++)
93 {
94 cout << "key=" << (*it).first << " value=" << it->second << endl;
95 }
96 }
97
98
99 int main()
100 {
101 test395();
102 test396();
103 //利用仿函数可以指定map容器的排序规则
104 //对于自定义数据类型,map必须要指定排序规则,同set容器
105
106 system("pause");
107 return 0;
108 }
