C++ std::list::crbegin
The std::list::crbegin
function returns a constant reverse iterator pointing to the last element of the list. This function is used for reverse traversal when the contents of the list should not be modified. If the list is empty, the returned reverse iterator is equal to crend()
.
Syntax of std::list::crbegin
const_reverse_iterator crbegin() const noexcept;
Parameters
The std::list::crbegin
function does not take any parameters.
Return Value
Returns a constant reverse iterator pointing to the last element of the list. If the list is empty, the returned iterator is equal to crend()
.
Exceptions
The std::list::crbegin
function does not throw exceptions as it is marked noexcept
. However, dereferencing the reverse iterator returned by crbegin()
when the list is empty results in undefined behavior. It is recommended to check if the list is empty before accessing elements.
Examples for std::list::crbegin
Example 1: Traversing a List in Reverse Using std::list::crbegin
This example demonstrates how to use crbegin()
and crend()
to traverse a list in reverse order without modifying its elements:
#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 fromcrbegin()
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.