C++ std::array::crend
The std::array::crend
function returns a constant reverse iterator pointing to one before the first element of the array (considered the end of the reversed array). This iterator ensures read-only access when traversing the array in reverse order. It is commonly used with crbegin()
to define a range for reverse iteration.
Syntax of std::array::crend
const_reverse_iterator crend() const noexcept;
Parameters
The std::array::crend
function does not take any parameters.
Return Value
Returns a constant reverse iterator pointing to one before the first element of the array, marking the end of reverse iteration. This ensures that the reverse traversal range ends at the appropriate point.
Examples for std::array::crend
Example 1: Reverse Iteration Using std::array::crend
This example demonstrates iterating through the elements of a std::array
in reverse order using crbegin()
and crend()
:
#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 it = arr.crbegin(); it != arr.crend(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
- Define an array: A
std::array
is initialized with elements{10, 20, 30, 40, 50}
. - Use
crend()
: Thecrend()
function provides a constant reverse iterator pointing to one before the first element of the array, marking the end of reverse iteration. - Reverse traversal: A for loop iterates from
crbegin()
tocrend()
, printing each element in reverse order. The constant reverse iterator ensures the array elements cannot be modified.
Output:
Array elements in reverse order: 50 40 30 20 10
Example 2: Using std::array::crend with a Standard Algorithm
This example demonstrates using std::array::crend
with std::count_if
to count elements greater than a given value in reverse order:
#include <iostream>
#include <array>
#include <algorithm>
int main() {
std::array<int, 5> arr = {1, 2, 3, 4, 5};
int count = std::count_if(arr.crbegin(), arr.crend(), [](int x) {
return x > 2;
});
std::cout << "Count of elements greater than 2 in reverse order: " << count << std::endl;
return 0;
}
Explanation:
- Original array: The array
arr
is initialized with elements{1, 2, 3, 4, 5}
. - Use
std::count_if
: Thestd::count_if
algorithm iterates through the reverse range defined bycrbegin()
andcrend()
, counting elements satisfying the conditionx > 2
. - Lambda function: The lambda function checks if each element is greater than 2.
- Output the result: The total count of elements matching the condition is displayed.
Output:
Count of elements greater than 2 in reverse order: 3
Exception Handling in std::array::crend
The std::array::crend
function does not throw exceptions as it is marked noexcept
. This ensures safe access to the reverse end iterator of the array.