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

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

</>
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.rbegin(); it != myList.rend(); ++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 reverse iterators: The rbegin() function provides a reverse iterator pointing to the last element, and rend() provides a reverse iterator one before the first element.
  3. Iterate through the list: The for loop iterates from rbegin() to rend(), 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:

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

  1. Define an empty list: An empty std::list named emptyList is created.
  2. Compare iterators: The rbegin() and rend() 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.

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.