c++逆序map怎么输出
时间: 2023-10-31 18:16:38 浏览: 73
逆序map可以使用反向迭代器(rbegin()和rend())进行输出。具体实现方法如下:
```c++
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, string> myMap;
myMap[1] = "one";
myMap[2] = "two";
myMap[3] = "three";
myMap[4] = "four";
// 使用反向迭代器输出
for (auto it = myMap.rbegin(); it != myMap.rend(); it++) {
cout << it->first << ": " << it->second << endl;
}
return 0;
}
```
输出结果为:
```
4: four
3: three
2: two
1: one
```
相关问题
c++中map逆序遍历
可以使用反向迭代器实现map的逆序遍历,示例代码如下:
```c++
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};
// 逆序遍历
for (auto it = myMap.rbegin(); it != myMap.rend(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
return 0;
}
```
输出结果为:
```
3: three
2: two
1: one
```
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()`进行的遍历是从最后一个键值对开始,按照键的逆序进行的。