21xrx.com
2025-03-24 12:33:51 Monday
文章检索 我的文章 写文章
C++中的map可以倒序遍历吗?
2023-06-24 14:04:32 深夜i     --     --
C++ map 倒序遍历

C++是一款广泛使用的编程语言,其标准库中提供了各种数据结构和算法来方便程序员开发。其中,map是一种常用的关联式容器,可以将键值映射到对应的数据上。然而,有时倒序遍历map也是必要的,那么C++中的map是否支持倒序遍历呢?

结论是,C++中的map是没有提供原生的倒序遍历功能的。不过,我们可以使用一些技巧来实现我们需要的倒序遍历。下面介绍几种实现倒序遍历map的方法:

方法一:利用reverse_iterator进行遍历

使用reverse_iterator可以实现对反向迭代器的遍历。具体做法如下:

#include <iostream>
#include <map>
using namespace std;
int main() {
  map<int, int> myMap{2, 5, 4};
  for (auto it = myMap.rbegin(); it != myMap.rend(); ++it)
    cout << it->first << " " << it->second << endl;
  
  return 0;
}

方法二:使用std::copy算法

使用std::copy算法在容器中复制元素,可以将map中的数据复制到一个vector中,并对该vector进行倒序遍历。代码如下:

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
  map<int, int> myMap{2, 6, 3};
  vector<pair<int,int>> vec(myMap.begin(),myMap.end());
  std::reverse(vec.begin(), vec.end());
  for (auto& p : vec)
    cout << p.first << " " << p.second << endl;
  
  return 0;
}

方法三:使用boost库

如果你使用的是boost库,则可以直接使用BOOST_FOREACH进行倒序遍历,无需自己写迭代器。代码如下:

#include <iostream>
#include <map>
#include <boost/foreach.hpp>
int main() {
  std::map<int, int> myMap{1, 6, 3};
  BOOST_REVERSE_FOREACH (auto kv, myMap)
    std::cout << kv.first << " " << kv.second << std::endl;
  
  return 0;
}

以上是三种实现倒序遍历map的方法,通过这些技巧,我们可以很方便地实现我们需要的遍历方式。

  
  

评论区

    相似文章