# How to traverse a STL map in reverse direction?

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 ` `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 ` `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 ` `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 ` `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 ` `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 ` `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 > 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 ` `#include `   `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`

Output

```25 -> 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 ` `#include `   `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`

Output

```25 -> GFG
15 -> Geeks
10 -> GeeksForGeeks```

Refer end for complexity analysis.

### Complexity Analysis:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Previous
Next