C++ std::array::rbegin
The std::array::rbegin
function returns a reverse iterator pointing to the last element of the array (considered the first element of the reversed array). This allows you to iterate over the elements of the array in reverse order.
Syntax of std::array::rbegin
reverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() const noexcept;
Parameters
The std::array::rbegin
function does not take any parameters.
Return Value
Returns a reverse iterator (or a constant reverse iterator for const
arrays) to the last element of the array, which is the first element in reverse order. If the array is empty, the returned iterator will be equal to std::array::rend
.
Examples for std::array::rbegin
Example 1: Traversing an Array in Reverse Using std::array::rbegin
This example demonstrates iterating through the elements of a std::array
in reverse order using rbegin()
and rend()
:
#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:
- Define an array: A
std::array
of size 5 is defined and initialized with the elements{10, 20, 30, 40, 50}
. - Use
rbegin()
andrend()
: Therbegin()
function provides a reverse iterator pointing to the last element of the array, andrend()
provides a reverse iterator pointing to one before the first element of the array. - 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::rbegin with Standard Algorithms
This example demonstrates using std::array::rbegin
with the std::copy
algorithm to print elements in reverse order:
#include <iostream>
#include <array>
#include <iterator>
#include <algorithm>
int main() {
std::array<int, 5> arr = {1, 2, 3, 4, 5};
std::cout << "Array elements in reverse order: ";
std::copy(arr.rbegin(), arr.rend(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
return 0;
}
Explanation:
- Original array: The array
arr
is initialized with elements{1, 2, 3, 4, 5}
. - Use
std::copy
: Thestd::copy
algorithm is used to copy elements from the range specified byrbegin()
andrend()
to an output stream iterator, which writes them to the console. - Reverse traversal: The
rbegin()
function provides the starting point for reverse iteration, andrend()
provides the endpoint.
Output:
Array elements in reverse order: 5 4 3 2 1
Exception Handling in std::array::rbegin
The std::array::rbegin
function does not throw exceptions as it is marked noexcept
. This ensures safe usage for reverse traversal operations.