Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate in reverse over a map in C++?

I'm having trouble iterating in reverse over a map in GCC C++. When I use a reverse iterator, it seems I can't assign anything to it - the compiler complains. I'm working around it with some awkward code using a forward iterator, but it's not very elegant. Any thoughts?

like image 298
Jack BeNimble Avatar asked Apr 08 '09 22:04

Jack BeNimble


People also ask

How do I iterate back from a map in C++?

The C++ function std::map::rbegin() returns a reverse iterator which points to the last element of the map. Reverse iterator iterates in reverse order that is why incrementing them moves towards beginning of map.

How do you iterate through a reverse vector?

So, to iterate over a vector in reverse direction, we can use the reverse_iterator to iterate from end to start. vector provides two functions which returns a reverse_iterator i.e. vector::rend() –> Returns a reverse iterator that points to the virtual element before the start of vector.

How do you reverse a traverse map in CPP?

map rbegin() function in C++ STL The rbegin() is a function in C++ STL. It returns a reverse iterator which points to the last element of the map. The reverse iterator iterates in reverse order and incrementing it means moving towards beginning of map.


2 Answers

Here's an example of iterating backward through a std::map:

#include <iostream> #include <map> #include <string>  int main() {     std::map<std::string, std::string> m;     m["a"] = "1";     m["b"] = "2";     m["c"] = "3";      for (auto iter = m.rbegin(); iter != m.rend(); ++iter) {         std::cout << iter->first << ": " << iter->second << std::endl;     } } 

If you are pre-C++11, you'll just need to spell out auto, which is:

std::map<std::string, std::string>::reverse_iterator 

Note that if you're using boost, you can use a range-based for loop with a reverse adapter:

#include <boost/range/adaptor/reversed.hpp>  for (auto& iter : boost::adaptors::reverse(m)) {     std::cout << iter.first << ": " << iter.second << std::endl; } 
like image 169
GManNickG Avatar answered Oct 05 '22 21:10

GManNickG


Since C++20 you can make use of the range adaptor std::views::reverse from the Ranges library. If you add this to a range-based for loop with structured binding, iterating backwards over an std::map could be done as follows:

#include <map> #include <ranges> #include <iostream>  int main() {     std::map<std::string, int> m = { {"a", 1}, {"b", 2}, {"c", 3} };      for (auto const& [k, v] : m | std::views::reverse)         std::cout << k << " => " << v << std::endl;      return 0; } 

Output:

c => 3
b => 2
a => 1

Code on Wandbox

like image 31
honk Avatar answered Oct 05 '22 22:10

honk