C++ std::array::rend

The std::array::rend function returns a reverse iterator pointing to one before the first element of the array (considered the end of the reversed array). This is useful when iterating through the array in reverse order, as it provides a boundary for reverse iteration.


Syntax of std::array::rend

</>
Copy
reverse_iterator rend() noexcept;
const_reverse_iterator rend() const noexcept;

Parameters

The std::array::rend function does not take any parameters.

Return Value

Returns a reverse iterator (or a constant reverse iterator for const arrays) pointing to one before the first element of the array. This iterator marks the end of reverse iteration.


Examples for std::array::rend

Example 1: Iterating in Reverse Using std::array::rend

This example demonstrates how to iterate through the elements of a std::array in reverse order using rbegin() and rend():

</>
Copy
#include <iostream>
#include <array>

int main() {
    std::array<int, 5> arr = {10, 20, 30, 40, 50};

    std::cout << "Array elements in reverse order: ";
    for (auto rit = arr.rbegin(); rit != arr.rend(); ++rit) {
        std::cout << *rit << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation:

  1. Define an array: A std::array of size 5 is defined and initialized with the elements {10, 20, 30, 40, 50}.
  2. Use rend() and rbegin(): The rend() function provides a reverse iterator pointing to one before the first element of the array, marking the end of the reverse iteration range.
  3. Iterate in reverse: A for loop is used to traverse the array in reverse order, accessing each element using the dereference operator *rit.

Output:

Array elements in reverse order: 50 40 30 20 10

Example 2: Using std::array::rend with a Standard Algorithm

This example demonstrates using std::array::rend with std::reverse_copy to copy elements in reverse order:

</>
Copy
#include <iostream>
#include <array>
#include <algorithm>
#include <vector>

int main() {
    std::array<int, 5> arr = {1, 2, 3, 4, 5};
    std::vector<int> reversed_arr(arr.size());

    std::reverse_copy(arr.rbegin(), arr.rend(), reversed_arr.begin());

    std::cout << "Reversed array elements: ";
    for (int x : reversed_arr) {
        std::cout << x << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation:

  1. Original array: The array arr is initialized with elements {1, 2, 3, 4, 5}.
  2. Use std::reverse_copy: The std::reverse_copy algorithm copies elements from the reverse range defined by rbegin() and rend() to the destination container, reversed_arr.
  3. Output the reversed array: A range-based for loop is used to print the elements of reversed_arr.

Output:

Reversed array elements: 1 2 3 4 5

Exception Handling in std::array::rend

The std::array::rend function does not throw exceptions as it is marked noexcept. This guarantees safe usage when accessing reverse iterators for the array.