In the previous article, we have discussed about C++ Map Insert Example. Let us learn how to Iterate a Map in Reverse Orde in C++ Program.
Iterate a Map in Reverse Order
In this article we will see how to iterate a map in reverse order.
As we know elements are stored in a sorted order in map.
For example, if the below elements need to be stored in map
{ "a", 1 },
{ "c", 3 },
{ "d", 4 },
{ "b", 2 }
Then it will be stored as below in the map.
{ "a", 1 }, { "b", 2 }, { "c", 3 }, { "d", 4 },
By using the reverse iterator of map we will iterate the map in reverse order.
std::map<std::string, int>::reverse_it
reverse_it moves in backward direction. So it will start from last element of the map and will move to first element of the map.Where,
- std::map::rbegin() – It will point to the last element of the map.
- std::map::rend() – It will point to the first element of the map.
#include <iostream>
#include <map>
#include <string>
#include <iterator>
int main()
{
// map of String & Int created & Initialized
std::map<std::string, int> sample_Map = {
{ "a", 1 },
{ "c", 3 },
{ "d", 4 },
{ "b", 2 }
};
// map iterator created
// which pointing to the end of map
std::map<std::string, int>::reverse_iterator it = sample_Map.rbegin();
// Iterating over the map using Iterator till start of map.
while (it != sample_Map.rend()) {
// key accessed
std::string word = it->first;
// value accessed
int count = it->second;
std::cout << word << " :: " << count << std::endl;
// Incrementing the Iterator to point to next entry
it++;
}
return 0;
}
Output : d :: 4 c :: 3 b :: 2 a :: 1