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

</>
Copy
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:

</>
Copy
#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:

  1. Define a list: A std::list named myList is initialized with elements {10, 20, 30, 40, 50}.
  2. Use constant reverse iterators: The crbegin() function provides a constant reverse iterator pointing to the last element, and crend() provides a constant reverse iterator pointing to one before the first element.
  3. Traverse the list: The for loop iterates from crbegin() to crend(), 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:

</>
Copy
#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:

  1. Define an empty list: An empty std::list named emptyList is created.
  2. Compare iterators: The crbegin() and crend() iterators are compared. Since the list is empty, they are equal.
  3. 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.