How to traverse a STL map in reverse direction?
Last Updated :
30 Mar, 2023
Map stores the elements in sorted order of keys. Now if we want to traverse it in reverse order we will use reverse_iterator of map.
Syntax:
map::reverse_iterator iterator_name;
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.
1. rbegin() : It returns the reverse_iterator pointing to last element of map.
2. rend() : It returns the reverse_iterator pointing to first element of map.
Now for traversing in reverse order we will iterate over the range b/w rbegin() & rend() using reverse_iterator.
Reverse Iteration in map:
Example:
Input: (10, "geeks"), (20, "practice"), (5, " contribute")
Output : (20, "practice"), (10, "geeks"), (5, " contribute")
CPP
// C++ program makes a map to iterate
// elements in reverse order.
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Creating & Initializing a map of String & Ints
map<int, string> mymap;
// Inserting the elements one by one
mymap.insert(make_pair(10, "geeks"));
mymap.insert(make_pair(20, "practice"));
mymap.insert(make_pair(5, "contribute"));
// Create a map reverse iterator
map<int, string>::reverse_iterator it;
// rbegin() returns to the last value of map
for (it = mymap.rbegin(); it != mymap.rend(); it++) {
cout << "(" << it->first << ", "
<< it->second << ")" << endl;
}
return 0;
}
Output:(20, practice)
(10, geeks)
(5, contribute)
We can also use auto to avoid remembering complex syntax.
CPP
// C++ program makes a map to iterate
// elements in reverse order with simpler
// syntax
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Creating & Initializing a map of String & Ints
map<int, string> mymap;
// Inserting the elements one by one
mymap.insert(make_pair(10, "geeks"));
mymap.insert(make_pair(20, "practice"));
mymap.insert(make_pair(5, "contribute"));
// rbegin() returns to the last value of map
for (auto it = mymap.rbegin(); it != mymap.rend(); it++) {
cout << "(" << it->first << ", "
<< it->second << ")" << endl;
}
return 0;
}
Output:(20, practice)
(10, geeks)
(5, contribute)
Refer end for complexity analysis.
Reverse Iteration Using map's key_type Range:
Another method to traverse a map in reverse order is to use map's key_type range, and traverse the keys in reverse order.
Example:
Input: (15, "Geeks"), (25, "GFG"), (10, "GeeksForGeeks")
Output : (25, "GFG"), (15, "Geeks"), (10, "GeeksForGeeks")
Below is the implementation:
C++
// C++ program makes a map to iterate
// elements in reverse order
// using map's key_type range
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Creating & Initializing a map of Ints & Strings
map<int, string> mymap;
// Inserting the elements one by one
mymap.insert(make_pair(15, "Geeks"));
mymap.insert(make_pair(25, "GFG"));
mymap.insert(make_pair(10, "GeeksForGeeks"));
// Print the content of the map in reverse order
for (auto it = mymap.rbegin()->first;
it >= mymap.begin()->first; --it) {
if (mymap.count(it))
cout << "(" << it << ", " << mymap[it] << ")"
<< endl;
}
return 0;
}
// This code is contributed by Susobhan Akhuli
Output(25, GFG)
(15, Geeks)
(10, GeeksForGeeks)
Refer end for complexity analysis.
Reverse Iteration in multimap:
Multimap is similar to map with an addition that multiple elements can have same keys. Rather than each element being unique, the key value and mapped value pair has to be unique in this case.
Example:
Input : (10, "geeks"), (20, "practice"), (5, "contribute"),
(20, "van"), (20, "watch"), (5, "joker")
Output: (20, "watch"), (20, "van"), (20, "practice"),
(10, "geeks"), (5, "joker"), (5, "contribute")
CPP
// C++ program makes a multimap to store
// elements in descending order.
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Creating & Initializing a multimap
// of Ints & String
multimap<int, std::string> mymap;
// Inserting the elements one by one
mymap.insert(make_pair(10, "geeks"));
mymap.insert(make_pair(20, "practice"));
mymap.insert(make_pair(5, "contribute"));
// Duplicates allowed
mymap.insert(make_pair(20, "van"));
mymap.insert(make_pair(20, "watch"));
mymap.insert(make_pair(5, "joker"));
for (auto it = mymap.rbegin(); it != mymap.rend(); it++) {
cout << "(" << it->first << ", "
<< it->second << ")" << endl;
}
return 0;
}
Output:(20, watch)
(20, van)
(20, practice)
(10, geeks)
(5, joker)
(5, contribute)
Refer end for complexity analysis.
Reverse Iteration in map without using rbegin() or rend() function:
We can use normal begin() and end() function to iterate the map in reverse order.
Example:
Input: (15, "Geeks"), (25, "GFG"), (10, "GeeksForGeeks")
Output : (25, "GFG"), (15, "Geeks"), (10, "GeeksForGeeks")
Below is the implementation:
C++
// C++ program makes a map to iterate
// elements in reverse order
// without using map.rbegin() and map.rend() functions
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Creating & Initializing a map of Ints & Strings
map<int, string> mymap;
// Inserting the elements one by one
mymap.insert(make_pair(15, "Geeks"));
mymap.insert(make_pair(25, "GFG"));
mymap.insert(make_pair(10, "GeeksForGeeks"));
// set iterator it as the end()
// which returns to the last value of map
auto it = mymap.end();
it--;
// Print the content of the map in reverse order
while (it != mymap.begin()) {
cout << "(" << it->first << ", " << it->second
<< ")" << endl;
it--;
if (it == mymap.begin())
cout << "(" << it->first << ", " << it->second
<< ")" << endl;
}
return 0;
}
// This code is contributed by Susobhan Akhuli
Output(25, GFG)
(15, Geeks)
(10, GeeksForGeeks)
Refer end for complexity analysis.
Reverse Iteration in map using vector:
We can create a vector with all the elements of the map, then use the std::reverse algorithm to reverse the order of the elements in the vector, then iterate through the vector to access the elements in the reversed order.
Input: (15, "Geeks"), (25, "GFG"), (10, "GeeksForGeeks")
Output : (25, "GFG"), (15, "Geeks"), (10, "GeeksForGeeks")
Below is the implementation:
C++
// C++ program makes a map to iterate
// elements in reverse order using vector
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Creating & Initializing a map of Ints & Strings
map<int, string> mymap;
// Inserting the elements one by one
mymap.insert(make_pair(15, "Geeks"));
mymap.insert(make_pair(25, "GFG"));
mymap.insert(make_pair(10, "GeeksForGeeks"));
// Create a vector with all the elements of the map
vector<pair<int, string> > v(mymap.begin(), mymap.end());
// Reverse the order of the elements in the vector
reverse(v.begin(), v.end());
// Iterate through the vector to access the elements in
// the reversed order
for (auto it : v) {
cout << "(" << it.first << ", " << it.second << ")" << endl;
}
return 0;
}
// This code is contributed by Susobhan Akhuli
Output(25, GFG)
(15, Geeks)
(10, GeeksForGeeks)
Refer end for complexity analysis.
Reverse Iteration in map using cbegin() and cend() :
cend() and cbegin() are member functions of the map container in the C++ Standard Template Library. cbegin() returns an iterator pointing to the first element in the container, while cend() returns an iterator pointing to the position just after the last element in the container. By using these functions, we can traverse the elements of a map in reverse order.
Input: (15, "Geeks"), (25, "GFG"), (10, "GeeksForGeeks")
Output: (25, "GFG"), (15, "Geeks"), (10, "GeeksForGeeks")
Below is the implementation:
C++
// C++ program makes a map to iterate
// elements in reverse order using cbegin() and cend()
#include <iostream>
#include <map>
using namespace std;
int main()
{
// Creating & Initializing a map of Ints & Strings
map<int, string> my_map;
// Inserting the elements one by one
my_map.insert(make_pair(15, "Geeks"));
my_map.insert(make_pair(25, "GFG"));
my_map.insert(make_pair(10, "GeeksForGeeks"));
// Traverse the map in reverse direction
for (auto it = my_map.cend(); it != my_map.cbegin();
it--) {
auto itr = it;
itr--;
cout << itr->first << " -> " << itr->second << endl;
}
return 0;
}
// This code is contributed by Susobhan Akhuli
Output25 -> GFG
15 -> Geeks
10 -> GeeksForGeeks
Refer end for complexity analysis.
Reverse Iteration in map using crbegin() and crend() :
crend() and crbegin() are member functions of the map container in the C++ Standard Template Library. They return constant reverse iterators to the last element and the first element of the container, respectively. By using these functions, we can traverse the elements of a map in reverse order.
Input: (15, "Geeks"), (25, "GFG"), (10, "GeeksForGeeks")
Output : (25, "GFG"), (15, "Geeks"), (10, "GeeksForGeeks")
Below is the implementation:
C++
// C++ program makes a map to iterate
// elements in reverse order using crbegin() and crend()
#include <iostream>
#include <map>
using namespace std;
int main()
{
// Creating & Initializing a map of Ints & Strings
map<int, string> my_map;
// Inserting the elements one by one
my_map.insert(make_pair(15, "Geeks"));
my_map.insert(make_pair(25, "GFG"));
my_map.insert(make_pair(10, "GeeksForGeeks"));
// Traverse the map in reverse direction
for (auto it = my_map.crbegin(); it != my_map.crend();
++it) {
cout << it->first << " -> " << it->second << endl;
}
return 0;
}
// This code is contributed by Susobhan Akhuli
Output25 -> GFG
15 -> Geeks
10 -> GeeksForGeeks
Refer end for complexity analysis.
Complexity Analysis:
Methods
| Time Complexity
| Auxiliary Space
|
---|
Using reverse Iteration in map
| O(N)
| O(1)
|
---|
Using map's key_type Range
| O(N)
| O(1)
|
---|
In multimap
| O(N)
| O(1)
|
---|
Without using rbegin() or rend() function
| O(N)
| O(1)
|
---|
Using vector
| O(N)
| O(N)
|
---|
using cbegin() and cend()
| O(N)
| O(1)
|
---|
using crbegin() and crend()
| O(N)
| O(1)
|
---|
Similar Reads
Map in C++ STL In C++, maps are associative containers that store data in the form of key value pairs sorted on the basis of keys. No two mapped values can have the same keys. By default, it stores data in ascending order of the keys, but this can be changes as per requirement.Example:C++#include <bits/stdc++.h
8 min read
Different Ways to Initialize a Map in C++ Initializing map refers to the process of assigning the initial values to the elements of map container. In this article, we will learn different methods to initialize the map in C++. Let's start from the easiest method:Using Initializer ListThe simplest way to initialize an std::map container is by
3 min read
Inserting Elements in a Map in C++ In C++, map stores unique key value pairs in sorted order and provides fast insert, delete and search operation. In this article, we will learn different methods to insert an element in a map in C++.The recommended method to insert an element in a map is by using map insert() method. Letâs take a lo
4 min read
Different ways to delete elements in std::map (erase() and clear()) This article deals with the deletion part of Maps. We can delete elements in std::map using two functions 1. Using erase() The erase() is used to erase the pair in the map mentioned in the argument, either its position, its value, or a range of numbers. We can use the erase function in the following
4 min read
Commonly Used Methods
Other Member Methods
Map and External Sorting Criteria/Comparator in C++ STL C++ Map is another commonly used STL container, it stores elements in a mapped fashion. Each element is stored as a pair having a key value and a mapped value. No two mapped values can have the same key values which means each key is unique. By default, key values in the map are in lexicographically
4 min read
Get Map Element at Offset in C++ STL Prerequisites: Map in C++ STL Since the map is not indexed as arrays or vectors sequential access is not possible in the map but to access an element at a particular offset. Example: inserted elements are { 'a',11 } , { 'b',12 } , { ' c ', 13 } then we can get { 'b', 12 } for 2 position. Methods to
3 min read
Search by value in a Map in C++ Given a set of N pairs as a (key, value) pairs in a map and an integer K, the task is to find all the keys mapped to the given value K. If there is no key value mapped to K then print "-1".Examples: Input: Map[] = { {1, 3}, {2, 3}, {4, -1}, {7, 2}, {10, 3} }, K = 3 Output: 1 2 10 Explanation: The 3
2 min read
Passing Map as Reference in C++ STL Prerequisite: Maps in C++ STL Pass by reference Elements in the map are in form of pairs where the first is key and another value, denoting key-value pairs. Also, all the key values are unique means no two elements can have the same key value. Passing maps by value is a costly task, costly in terms
3 min read