I'm trying to print the contents of an unordered_map in reverse order, but it doesn't have rbegin or rend, so you can't use reverse_iterator. How is reversing of the unordered_map supposed to be done?
EDIT (from comment): I want the keys to be in the order they were inserted in, hence I cant use map. The keys appear to stay in the insertion order, but I need them reversed.
Iterating over a map by using STL Iterator: By creating an iterator of std::map and initializing it to the starting of map and visiting upto the end of map we can successfully iterate over all the elements of map.
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.
Just reading the first sentence in your question gives you the answer:
I'm trying to print the contents of an
unordered_map
in reverse order
You cannot print in any order because, well, it is unordered. It makes no sense talking about order in an unordered structure. It does not matter how the contents of an unordered_map
are organised internally: this is an implementation detail and you cannot access it. To the outside world, an unordered_map
exhibits no order at all and you cannot expect it to do it.
You can cobble up your own pair of reverse iterators from any pair of bidirectional iterators:
std::reverse_iterator rbegin(first);
std::reverse_iterator rend(last);
As @Tin suggested, this doesn't work. Never mind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With