1 #include <iostream>
2 #include <cstdio>
3 #include <map>
4 #include <utility>
5 #include <algorithm>//定义pair的头文件
6 using namespace std;
7 #define N 5
8
9 map<int,int> m;
10
11 void pm()//map输出函数
12 {
13 map<int,int>::iterator i1;
14 for (i1=m.begin();i1!=m.end();i1++)
15 {
16 printf("%d %d\n",i1->first,i1->second);
17 }
18 printf("\n");
19 }
20
21 int main()
22 {
23 int i;
24
25 pair<int,string> p(0,"aa");//pair的定义和对象
26 printf("%d %s\n",p.first,p.second.c_str());
27 pair<int,string> p1(1,"bb");
28 printf("%d %s\n",p1.first,p1.second.c_str());
29
30 for (i=0;i<N;i++)//使用下标插入,若不存在该元素,则会在map中插入
31 {
32 m[i]=i;
33 }
34 pm();
35
36 for (i=N;i<2*N;i++)//用insert函数插入
37 {
38 m.insert(make_pair(i,i));
39 }
40 pm();
41
42 if (m.count(0))//查找该元素是否存在
43 {
44 printf("yes\n");
45 }
46 else
47 {
48 printf("no\n");
49 }
50
51 if (m.count(10))
52 {
53 printf("yes\n");
54 }
55 else
56 {
57 printf("no\n");
58 }
59
60 map<int,int>::iterator f,f1;
61 f=m.find(0);//返回所找元素的迭代器
62 f1=m.find(10);
63 if (f!=m.end())
64 {
65 f->second=f->second+N;
66 }
67 else
68 {
69 printf("no\n");
70 }
71 if (f1!=m.end())
72 {
73 f->second=f->second+N;
74 }
75 else
76 {
77 printf("no\n");
78 }
79 pm();
80
81 m.erase(9);
82 m.erase(m.begin());
83 pm();
84
85 printf("%d\n",m.empty());//map为空,返回true
86 printf("%d\n",(int)m.size());//返回元素个数
87
88 map<int,int> m1;
89 swap(m,m1);//交换两个map
90 pm();
91 for (f=m1.begin();f!=m1.end();f++)
92 {
93 printf("%d %d\n",f->first,f->second);
94 }
95
96
97 return 0;
98 }