map操作

map初始化
1、直接赋值

map[key]=value;

2、用insert添加pair类型的元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

#include<map>
#include<string>
#include<iostream>

using namespace::std;

int main()
{
//直接赋值法
map<string, int> m1;
m1[string("abc")] = 1;
m1[string("defg")] = 2;

//用insert添加
map<string, int> m2;
m2.insert({ string("abc"), 1 });
m2.insert(make_pair(string("defg"), 2));
m2.insert(pair<string, int>(string("hijk"), 3));

//打印 m1,m2
auto it1 = m1.begin();
cout << "m1:" << endl;
while (it1 != m1.end())
{
cout << it1->first << " " << it1->second << endl;
it1++;
}
cout <<"m2:" << endl;
auto it2 = m2.begin();
while (it2 != m2.end())
{
cout << it2->first << " " << it2->second << endl;
it2++;
}
system("pause");
return 0;
}