#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> mp;
mp["张三"] = 21;
mp["李四"] = 19;
mp["王五"] = 35;
// 方式一、迭代器
cout << "方式一、迭代器" << endl;
for (auto it = mp.begin(); it != mp.end(); it++) {
cout << it -> first << " " << it -> second << endl;
}
//或者写为
cout<<"\n";
cout << "方式一、迭代器" << endl;
map<string,int>::iterator it= mp.begin();
for(;it!=mp.end();it++){
cout<< it->first<<" "<<it->second<<endl;
}
cout<<"\n";
// 方式二、range for C++ 11版本及以上
cout << "方法二、 range for" << endl;
for (auto it : mp) {
cout << it.first << " " << it.second << endl;
}
return 0;
}
代码中仅列举了map的遍历方法,其他同理。