In this article we will discuss how to iterate a map in reverse order.

Map store the elements in sorted order of keys. For example, if you store following elements in map i.e.

It will internally store the elements in sorted order of keys i.e.

Iterating over a map will result in above order i.e. sorted order of keys. Now what if we want to iterate a map in reverse direction ?

Iterating a map in reverse order

To Iterate a map in reverse order we will use reverse_iterator of map i.e.

Reverse Iterator

Reverse Iterator of map moves in backward direction on increment. So, we will point the reverse_iterator to the last element of map and then keep on incrementing it until it reaches the first element. To do this we will use 2 member functions of std::map i.e.

std::map::rbegin()

It returns the reverse_iterator pointing to last element of map.

std::map::rend()

It returns the reverse_iterator pointing to first element of map.

Now, to loop back in reverse direction on a map. Iterate over the range b/w rbegin() & rend() using reverse_iterator.

Checkout complete example as follows,

Output:

To compile the above code on linux. Use following command,

g++ -std=c++11 example.cpp