C++ std::array::cend
The std::array::cend
function returns a constant iterator pointing to one past the last element of the array. This iterator ensures read-only access to the array elements and is typically used with cbegin()
to traverse the array in a safe, non-modifiable manner.
Syntax of std::array::cend
const_iterator cend() const noexcept;
Parameters
The std::array::cend
function does not take any parameters.
Return Value
Returns a constant iterator pointing to one past the last element of the array. This marks the end of the array when traversing with constant iterators.
Examples for std::array::cend
Example 1: Traversing an Array Using std::array::cend
This example demonstrates iterating through the elements of a std::array
using cbegin()
and cend()
:
#include <iostream>
#include <array>
int main() {
std::array<int, 5> arr = {10, 20, 30, 40, 50};
std::cout << "Array elements: ";
for (auto it = arr.cbegin(); it != arr.cend(); ++it) {
std::cout << *it << " ";
}
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
cend()
: Thecend()
function provides a constant iterator pointing to one past the last element of the array. - Iterate through the array: A for loop is used to traverse the array, with
cbegin()
as the starting point andcend()
as the endpoint. - Read-only access: The constant iterators ensure that the array elements cannot be modified during iteration.
Output:
Array elements: 10 20 30 40 50
Example 2: Using std::array::cend with a Standard Algorithm
This example demonstrates using std::array::cend
with the std::find
algorithm to locate an element in a std::array
:
#include <iostream>
#include <array>
#include <algorithm>
int main() {
std::array<int, 5> arr = {1, 2, 3, 4, 5};
int target = 3;
auto it = std::find(arr.cbegin(), arr.cend(), target);
if (it != arr.cend()) {
std::cout << "Element " << target << " found at position "
<< std::distance(arr.cbegin(), it) << std::endl;
} else {
std::cout << "Element " << target << " not found." << std::endl;
}
return 0;
}
Explanation:
- Original array: The array
arr
is initialized with elements{1, 2, 3, 4, 5}
. - Use
std::find
: Thestd::find
algorithm searches for the target element in the range defined bycbegin()
andcend()
. - Check the result: If the element is found, the iterator
it
points to its position. Thestd::distance
function calculates its index. - Output the result: The result of the search is displayed, indicating whether the element was found and, if so, its position.
Output:
Element 3 found at position 2
Exception Handling in std::array::cend
The std::array::cend
function does not throw exceptions as it is marked noexcept
. This ensures safe usage when accessing the end of a constant iterator range.