The C++ map rend method is employed to retrieve an iterator pointing to the end of the map in reverse order. This refers to the element prior to the first element in the reverse sequence, rather than the last element. When utilizing reverse iterators, traversal of the container happens in the reverse direction, moving from the end towards the beginning.
The rbegin function provides a reverse iterator pointing to the final element within the container. Conversely, the rend method serves as a boundary indicator, denoting the location just before the initial element of the map.
Note:- This is a placeholder. No element exists in this location, and attempting to access it is undefined behavior.
Syntax
It has the following syntax:
reverse_iterator rend(); //until C++ 11
reverse_iterator rend() const; //until C++ 11
reverse_iterator rend() noexcept; //since C++ 11
reverse_iterator rend() const noexcept; //since C++ 11
Parameter:
It does not contain any parameters.
Return value:
It provides a reverse iterator pointing to the element that precedes the first element in the reversed container.
Features of the crend function in C++
There are several features of the crend function in C++ . Some of them are as follows:
- The rend function does not refer to an actual element; it is a boundary marker.
- It should always be used in combination with rbegin .
- The rend function is very useful when we need to process items in a reversed order.
- It has constant time complexity, so no performance overhead.
- It supports both modifiable and unmodifiable map objects.
C++ map rend function example
Let's consider a scenario to demonstrate the rend function within C++.
Example
#include <iostream>
#include <map>
using namespace std;
int main ()
{
map<char,int> mymap;
mymap['x'] = 100;
mymap['y'] = 200;
mymap['z'] = 300;
// show content:
map<char,int>::reverse_iterator rit;
for (rit=mymap.rbegin(); rit!=mymap.rend(); ++rit)
cout << rit->first << " = " << rit->second << '\n';
return 0;
}
Output:
z = 300
y = 200
x = 100
Explanation:
In the previously mentioned scenario, the rend method is employed to provide a reverse iterator pointing to the element succeeding the last element in the reversed container. As maps organize elements based on the sorted order of keys, traversing through a map will yield the aforementioned sequence, specifically, the sorted order of keys.
Iterating Over a Map in Reverse Order Using rbegin and rend with a While Loop
Let's explore a basic illustration for traversing through the map in reverse sequence by employing a while loop in C++.
Example
#include <iostream>
#include <map>
#include <string>
#include <iterator>
using namespace std;
int main() {
// Creating & Initializing a map of String & Ints
map<string, int> mapEx = {
{ "aaa", 10 },
{ "ddd", 11 },
{ "bbb", 12 },
{ "ccc", 13 }
};
// Create a map iterator and point to the end of the map
map<string, int>::reverse_iterator it = mapEx.rbegin();
// Iterate over the map using Iterator till the beginning.
while (it != mapEx.rend()) {
// Accessing KEY from the elemencpp tutorialed by it.
string word = it->first;
// Accessing VALUE from the elemencpp tutorialed by it.
int count = it->second;
cout << word << " :: " << count << endl;
// Increment the Iterator to point to the next entry
it++;
}
return 0;
}
Output:
ddd :: 11
ccc :: 13
bbb :: 12
aaa :: 10
Explanation:
In the previous instance, a while loop is employed to traverse the map in reverse sequence. The reverse iterator initiates from the final element and progresses towards the initial one, displaying every key-value pair until all elements are handled.
Traversing a Map in Reverse Order Using rbegin and rend in C++
Let's consider an instance to demonstrate how to iterate through a map in reverse sequence by utilizing the rbegin and rend methods in C++.
Example
#include <iostream>
#include <map>
using namespace std;
int main(void) {
/* Initializer_list constructor */
map<char, int> m = {
{'a', 1},
{'b', 2},
{'c', 3},
{'d', 4},
{'e', 5},
};
cout << "Map contains following elements in reverse order:" << endl;
for (auto it = m.rbegin(); it != m.rend(); ++it)
cout << it->first << " = " << it->second << endl;
return 0;
}
Output:
Map contains following elements in reverse order:
e = 5
d = 4
c = 3
b = 2
a = 1
Explanation:
In this instance, we illustrate the process of iterating through a C++ map in reverse by employing the rbegin and rend functions. Initially, a map is set up with key-value pairs, followed by the utilization of a reverse iterator to retrieve elements beginning from the final key to the initial one. Subsequently, the application displays the map elements in a descending sequence based on keys.
C++ Program to Display Map Elements in Reverse Order and Find the Highest Salary Using rbegin
Let's consider an illustration to showcase map components in reverse sequence and determine the maximum salary using the rbegin method in C++.
Example
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main ()
{
map<int,int> emp = {
{ 1000, 10},
{ 2500, 20 },
{ 4500, 30 },
{ 3000, 40 },
{ 5500, 50 }};
cout << "Salary" << " | " << "ID" << '\n';
cout<<"______________________\n";
map<int,int>::reverse_iterator rit;
for (rit=emp.rbegin(); rit!=emp.rend(); ++rit)
cout << rit->first << " | " << rit->second << '\n';
auto ite = emp.rbegin();
cout << "\nHighest salary: "<< ite->first <<" \n";
cout << "ID is: "<< ite->second << "\n";
return 0;
}
Output:
Salary | ID
______________________
5500 | 50
4500 | 30
3000 | 40
2500 | 20
1000 | 10
Highest salary: 5500
ID is: 50
Explanation:
In the previous scenario, a map named emp is created with salaries as keys and IDs as values. This setup leverages the inherent sorting feature of maps, facilitating the retrieval of the ID associated with the highest salary.
Use Cases of map::rend
There are several use cases of the map::rend function in C++. Some of them are as follows:
- It is very useful if we want to process elements from last to first.
- It can be utilized to print elements in reverse order of keys.
- Reverse iteration may be useful at times in verifying conditions from the end element to the first.
- It can be integrated smoothly with STL algorithms that take iterators as arguments, such as findif, foreach, etc., in reverse.
Difference between begin, end, and rend
There exist significant disparities among the begin, end, and rend functions in C++. Some key distinctions are outlined below:
| Iterator | Position It Refers to | Points To Valid Element | Usage Context | Dereference Safety |
|---|---|---|---|---|
| begin() | First element in the container | Yes | Start of forward iteration | Safe |
| end() | One-past-the-last element (non-existent) | No | Boundary for forward iteration | Undefined behavior (unsafe) |
| rend() | One-before-the-first element (non-existent) | No | Boundary for reverse iteration | Undefined behavior (unsafe) |
Conclusion
In summary, the C++ map::rend method plays a crucial role within the Standard Template Library. It serves as a vital element in facilitating reverse iteration by providing a stopping point for traversing from the last element to the first. While it doesn't point to a specific element, the rend function ensures the correct operation of reverse loops and algorithms.
C++ Map rend function FAQs
1) Can we dereference rend in C++?
No. Accessing the rend function without dereferencing results in undefined behavior as it does not point to a valid element.
2) Why do we have both end and rend in C++?
They offer balance in both forward and reverse traversal. The end method ensures that loops continue forward without stopping, while rend ensures loops keep moving backward without halting.
What does rend return when the map is empty?
In a map with no elements, the rend function is identical to rbegin. Both iterators point to the same position since the map is empty.
4) Can rend be used with algorithms in C++?
Yes, the rend and rbegin functions allow algorithms to iterate in reverse through the container, a functionality that is not possible with begin and end.
5) Is rend supported in unordered_map?
No, the unordered_map provides begin and end methods, but it does not support reverse iterators like rend.