c++ map倒序遍历
时间: 2023-09-06 13:12:47 浏览: 121
你可以使用`std::map`的`rbegin()`和`rend()`迭代器来实现倒序遍历。以下是一个示例代码:
```cpp
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap = "one";
myMap = "two";
myMap = "three";
for (auto it = myMap.rbegin(); it != myMap.rend(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
return 0;
}
```
这段代码创建了一个`std::map`对象`myMap`,并向其中插入了一些键值对。然后,使用反向迭代器`rbegin()`和`rend()`循环遍历`myMap`,输出每个键值对的内容。输出结果为:
```
3: three
2: two
1: one
```
请注意,使用`rbegin()`和`rend()`进行的遍历是从最后一个键值对开始,按照键的逆序进行的。
相关问题
map倒序遍历c++
在C++中,可以使用reverse_iterator来实现map的倒序遍历。具体实现方法如下:
1. 正向遍历map:
```
map<int, int> mymap;
map<int, int>::iterator it;
for(it=mymap.begin();it!=mymap.end();it++){
cout << it->first << " " << it->second << endl;
}
```
2. 逆向遍历map:
```
map<int, int> mymap;
map<int, int>::reverse_iterator it;
for(it=mymap.rbegin();it!=mymap.rend();it++){
cout << it->first << " " << it->second << endl;
}
```
其中,rbegin()函数返回一个指向map末尾的reverse_iterator,rend()函数返回一个指向map开头的reverse_iterator。通过reverse_iterator的方式,可以实现map的倒序遍历。
c++迭代器倒序遍历
使用向迭代器可以实现C++中的迭代器倒序遍历。具体使用方法如下:
```cpp
for(std::set<int>::reverse_iterator it2=myvec.rbegin(); it2 != myvec.rend(); it2++) {
cout<<*it2<<endl;
}
```
需要注意的是,迭代器类型必须使用`reverse_iterator`。