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.
{"aaa", 10}, {"ddd", 11}, {"bbb", 12}, {"ccc", 13}
It will internally store the elements in sorted order of keys i.e.
{"aaa", 10}, {"bbb", 12}, {"ccc", 13}, {"ddd", 11},
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 ?
Frequently Asked:
Iterating a map in reverse order
To Iterate a map in reverse order we will use reverse_iterator of map i.e.
Reverse Iterator
std::map<std::string, int>::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()
reverse_iterator rbegin();
It returns the reverse_iterator pointing to last element of map.
std::map::rend()
reverse_iterator rend();
It returns the reverse_iterator pointing to first element of map.
Best Resources to Learn C++:
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,
#include <iostream> #include <map> #include <string> #include <iterator> int main() { // Creating & Initializing a map of String & Ints std::map<std::string, int> mapOfWordCount = { { "aaa", 10 }, { "ddd", 11 }, { "bbb", 12 }, { "ccc", 13 } }; // Create a map iterator and point to the end of map std::map<std::string, int>::reverse_iterator it = mapOfWordCount.rbegin(); // Iterate over the map using Iterator till beginning. while (it != mapOfWordCount.rend()) { // Accessing KEY from element pointed by it. std::string word = it->first; // Accessing VALUE from element pointed by it. int count = it->second; std::cout << word << " :: " << count << std::endl; // Increment the Iterator to point to next entry it++; } return 0; }
Output:
ddd :: 11 ccc :: 13 bbb :: 12 aaa :: 10
To compile the above code on linux. Use following command,
g++ -std=c++11 example.cpp
Leave a Reply
You must be logged in to post a comment.