STL中map的遍历

转自:http://www.cnblogs.com/kaitoex/p/6081980.html

map作为STL中的映射容器非常好用,我们来说一下map的遍历。

map.first为key值,map.second为value值,key不可修改,value可修改。

定义一个迭代指针iter,使其指向map,实现对map的遍历。

复制代码
 1 #include <iostream>
 2 #include <map>
 3 #include <string>
 4 
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     map<string,int>M;
10     M["Kaito"]=1;
11     M["Aoko"]=2;
12     M["Shinichi"]=3;
13     M["Lan"]=4;
14     map<string,int>::iterator iter;//定义一个迭代指针iter
15     for(iter=M.begin(); iter!=M.end(); iter++)
16         cout<<iter->first <<"->"<<iter->second<<endl;
17     return 0;
18 }
复制代码

运行结果:

我们可以看出,map自动对key值按ascii码顺序进行了排序,而并不是以输入顺序记录。


猜你喜欢

转载自blog.csdn.net/m0_37290785/article/details/80167375