c++ map遍历方法
时间: 2023-12-15 09:49:25 浏览: 38
C++中的map可以使用迭代器进行遍历。以下是两种常用的遍历方法:
方法一:使用auto关键字遍历
```c++
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, string> myMap;
myMap[1] = "apple";
myMap[2] = "banana";
myMap[3] = "cherry";
// 使用auto关键字遍历
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
cout << it->first << " : " << it->second << endl;
}
return 0;
}
```
方法二:使用迭代器遍历
```c++
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, string> myMap;
myMap[1] = "apple";
myMap[2] = "banana";
myMap[3] = "cherry";
// 使用迭代器遍历
map<int, string>::iterator it;
for (it = myMap.begin(); it != myMap.end(); ++it) {
cout << it->first << " : " << it->second << endl;
}
return 0;
}
```