C++ std::list::crend
The std::list::crend
function returns a constant reverse iterator pointing to the position one before the first element of the list. It acts as a marker for the end of reverse iteration and is used in conjunction with crbegin()
to iterate over the list in reverse order without modifying its elements. The iterator returned by crend()
is not dereferenceable.
Syntax of std::list::crend
const_reverse_iterator crend() const noexcept;
Parameters
The std::list::crend
function does not take any parameters.
Return Value
Returns a constant reverse iterator pointing to the position one before the first element of the list. This iterator is typically used to mark the end of reverse iteration.
Exceptions
The std::list::crend
function does not throw exceptions as it is marked noexcept
. However, dereferencing the iterator returned by crend()
results in undefined behavior, as it points to a position before the first element of the list.
Examples for std::list::crend
Example 1: Reverse Traversal Using std::list::crend
This example demonstrates how to use crbegin()
and crend()
to traverse a list in reverse order:
#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.crbegin(); it != myList.crend(); ++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 constant reverse iterators: The
crbegin()
function provides a constant reverse iterator pointing to the last element, andcrend()
provides a constant reverse iterator pointing to one before the first element. - Traverse the list: The for loop iterates from
crbegin()
tocrend()
, 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 crbegin()
and crend()
behave when the list is empty:
#include <iostream>
#include <list>
int main() {
std::list<int> emptyList;
if (emptyList.crbegin() == emptyList.crend()) {
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
crbegin()
andcrend()
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.