Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing or reverse iterating an unordered_map

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.

like image 659
user1866033 Avatar asked Nov 30 '12 10:11

user1866033


People also ask

Can you iterate over unordered_map?

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.

How do I reverse a 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

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.

like image 173
Gorpik Avatar answered Sep 22 '22 20:09

Gorpik


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.

like image 38
Pete Becker Avatar answered Sep 19 '22 20:09

Pete Becker