map创建

1
map<int,string>map

初始化列表

1
2
3
4
5
6
7
8
9
map<int,string>map2={

​ {1,"Alice"},

​ {2,"Bob"},

​ {3,"Charlie"}

};

map插入

1
2
3
4
5
6
7
map<int,string>studentMap;

//使用下列操作符(如果键存在则修改,不存在则插入)

studentMap[103]="mike";

studentMap[104]="Sarah";

访问元素

1
2
3
4
5
6
7
8
9
10
11
12
13
map<int,string>studentMap={

​ {101,"Tom"},

​ {102,"jerry"},

​ {103,"Mike"}

};

//1.使用下标操作符{如果键不存在会创新}

cout<<studentMap[101]<<endl;//输出:Tom

遍历map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
map<int,string>studentMap={

​ {101,"Tom"},

​ {102,"jerry"},

​ {103,"Mike"}

};

//1.使用迭代器

cout<<"使用迭代器遍历:"<<endl;

fbr(auto it=studentMap.begin();it!=studentMap.end();++it){

cout<<"ID:"<<it->first<<",Name:"<<it->second<<endl;}