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碼順序進行了排序,而並不是以輸入順序記錄。