c++的map中遍历
时间: 2023-12-15 07:33:20 浏览: 85
C++中的map可以使用迭代器进行遍历,以下是两种常见的遍历方式:
1.正向遍历
```c++
#include <map>
#include <iostream>
using namespace std;
int main() {
map<int, string> ss;
ss[0] = "nihao";
ss[1] = "hello";
ss[2] = "cpp";
map<int, string>::iterator it;
for (it = ss.begin(); it != ss.end(); it++) {
cout << it->first << " " << it->second << endl;
}
return 0;
}
```
输出:
```
0 nihao
1 hello
2 cpp
```
2.反向遍历
```c++
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main() {
map<int, string> mapStudent;
mapStudent[1] = "student_one";
mapStudent[2] = "student_two";
mapStudent[3] = "student_three";
map<int, string>::reverse_iterator iter;
for (iter = mapStudent.rbegin(); iter != mapStudent.rend(); iter++) {
cout << iter->first << " " << iter->second << endl;
}
return 0;
}
```
输出:
```
3 student_three
2 student_two
1 student_one
```
阅读全文