In C++, std::array::cend() returns a read-only iterator that points one place after the last element. It does not point to a real element, it only marks the end of the range.
Use it as the stop mark in loops that start with cbegin(). Include <array> to use it.
This is a member of std::array<T, N>, not of a plain C array and not of std::vector. A std::array has a fixed size N that is part of its type, and it lives on the stack like a normal variable.
Syntax
Call cend with empty brackets. It takes no arguments.
C++
for (auto it = nums.cbegin(); it != nums.cend(); ++it) {
// read *it
}
Call
What it does
nums.cend()
Returns a read-only iterator just after the last element.
nums.cend() - nums.cbegin()
Counts the elements. For an array this is the same as size().
Never write *nums.cend(). It points past the data.
Library declarations
C++
const_iterator cend() const noexcept;
Parameters
Parameter
Description
None
cend() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
Const iterator
A const_iterator to the position after the last element. For std::array<T, 0> it equals cbegin().
C++ Examples
Example 1 — Loop Until cend()
Print every price in a read-only loop.
C++
#include <array>
#include <iostream>
int main() {
std::array<int, 3> prices = {99, 149, 199};
for (auto it = prices.cbegin(); it != prices.cend(); ++it) {
std::cout << "Price: " << *it << '\n';
}
return 0;
}
Output
Price: 99
Price: 149
Price: 199
How It Works
The loop starts at cbegin(), which is the first price.
The condition it != prices.cend() keeps going until the end mark.
Each pass prints one price, so you see three lines.
Example 2 — Count Matches with std::count_if
Pass cbegin() and cend() to count items that match a rule.
C++
#include <algorithm>
#include <array>
#include <iostream>
int main() {
std::array<int, 5> nums = {3, 8, 12, 5, 20};
int big = std::count_if(nums.cbegin(), nums.cend(),
[](int n) { return n > 5; });
std::cout << "Numbers above 5: " << big << '\n';
return 0;
}
Output
Numbers above 5: 3
How It Works
The two iterators tell count_if to look at the whole array.
The small function n > 5 is tested on every element.
8, 12, and 20 pass the test, so the answer is 3.
Example 3 — Empty Range: cbegin() == cend()
An array with zero elements has nothing to loop over.