C++ std::list::rend
The std::list::rend
function returns a reverse iterator pointing to the element one position before the first element of the std::list
. This iterator acts as a marker for the reverse end of the list and is used in conjunction with rbegin()
for reverse iteration. The iterator returned by rend()
is not dereferenceable.
Syntax of std::list::rend
reverse_iterator rend() noexcept;
const_reverse_iterator rend() const noexcept;
Parameters
The std::list::rend
function does not take any parameters.
Return Value
Returns a reverse iterator (or a constant reverse iterator for const
lists) pointing to the position one before the first element of the list. This iterator is used to mark the end of reverse iteration.
Exceptions
The std::list::rend
function does not throw exceptions as it is marked noexcept
.
Examples for std::list::rend
Example 1: Reverse Traversal Using std::list::rend
This example demonstrates iterating through the elements of a std::list
in reverse order using rbegin()
and rend()
:
#include <iostream>
#include <list>
int main() {
std::list<int> myList = {10, 20, 30, 40, 50};
std::cout << "List elements in reverse: ";
for (auto it = myList.rbegin(); it != myList.rend(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
- Define a list: A
std::list
namedmyList
is initialized with elements{10, 20, 30, 40, 50}
. - Use reverse iterators: The
rbegin()
function provides a reverse iterator pointing to the last element, andrend()
provides a reverse iterator one before the first element. - Iterate through the list: The
for
loop iterates fromrbegin()
torend()
, accessing and printing each element using the dereference operator (*it
).
Output:
List elements in reverse: 50 40 30 20 10
Example 2: Checking Reverse Iteration with Empty List
This example demonstrates how rbegin()
and rend()
behave when the list is empty:
#include <iostream>
#include <list>
int main() {
std::list<int> emptyList;
if (emptyList.rbegin() == emptyList.rend()) {
std::cout << "The list is empty. No elements to iterate in reverse." << std::endl;
}
return 0;
}
Explanation:
- Define an empty list: An empty
std::list
namedemptyList
is created. - Compare iterators: The
rbegin()
andrend()
iterators are compared. Since the list is empty, they are equal. - Output message: A message is printed indicating that the list is empty and there are no elements to iterate in reverse.
Output:
The list is empty. No elements to iterate in reverse.
Exception Handling in std::list::rend
The std::list::rend
function does not throw exceptions as it is marked noexcept
. However, dereferencing the reverse iterator returned by rend()
results in undefined behavior. It is recommended to use rend()
only as a marker for the end of reverse iteration.