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

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

</>
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.