c++中 遍历map的三种方式

//遍历map的三种方式
//by 鸟哥

#include
#include
#include

using namespace std;

int main(){
    map<int,string> m{};
    m[0]="aaa";
    m[1]="bbb";
    m[2]="ccc";

    map<int,string>::iterator it;

    //方式一
    cout<<"方式一:"<<endl;
    for(auto &t : m){
        cout<<"key:"<<t.first<<" value:"<<t.second<<endl;
    }
    
    //方式二
    cout<<"方式二:"<<endl;
    for(map<int,string>::iterator iter = m.begin(); iter != m.end(); ++iter){
        cout<<"key:"<<iter->first<<" value:"<<iter->second<<endl;
    }

    //第三种
    cout<<"方式三:"<<endl;
    map<int,string>::iterator iter=m.begin();
    while(iter != m.end()){
        cout<<"key:"<<iter->first<<" value:"<<iter->second<<endl;
        ++iter;
    }

}

运行结果:

方式一:
key:0 value:aaa
key:1 value:bbb
key:2 value:ccc
方式二:
key:0 value:aaa
key:1 value:bbb
key:2 value:ccc
方式三:
key:0 value:aaa
key:1 value:bbb
key:2 value:ccc

你可能感兴趣的:(c++,map,代码示例)