map倒序遍历c++
时间: 2023-11-15 15:02:38 浏览: 68
在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++ map倒序遍历
你可以使用`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()`进行的遍历是从最后一个键值对开始,按照键的逆序进行的。
JAVA map倒序遍历
在 Java 中,可以使用 TreeMap 来实现 Map 的倒序遍历。TreeMap 会按照 key 的自然顺序排序(如果 key 是数字,则按照数字大小排序;如果 key 是字符串,则按照字典顺序排序)。如果需要倒序遍历,只需要使用 TreeMap 的 descendingMap() 方法获取一个倒序的 Map。下面是示例代码:
```
import java.util.TreeMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// 创建一个 TreeMap,并向其中添加一些元素
TreeMap<String, Integer> map = new TreeMap<>();
map.put("apple", 10);
map.put("orange", 5);
map.put("banana", 8);
// 获取一个倒序的 Map
Map<String, Integer> descendingMap = map.descendingMap();
// 遍历倒序的 Map
for (Map.Entry<String, Integer> entry : descendingMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
```
输出结果为:
```
orange: 5
banana: 8
apple: 10
```