In C++, std::array::cbegin() returns a const_iterator that points to the first element. The letter c stands for const, so you can read through the iterator but not change the element.
It is useful when you want the compiler to protect your data from accidental changes. 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 cbegin with empty brackets. It takes no arguments.
C++
auto it = nums.cbegin();
int first = *it;
Call
What it does
nums.cbegin()
Returns a read-only iterator to the first element.
*nums.cbegin()
Reads the first element. Writing to it will not compile.
cbegin() works even when the array itself is not const.
Library declarations
C++
const_iterator cbegin() const noexcept;
Parameters
Parameter
Description
None
cbegin() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
Const iterator
A const_iterator to the first element. For std::array<T, 0> it is equal to cend().
C++ Examples
Example 1 — Read-Only Loop
Print all elements without any chance of changing them.
C++
#include <array>
#include <iostream>
int main() {
std::array<int, 3> nums = {10, 20, 30};
for (auto it = nums.cbegin(); it != nums.cend(); ++it) {
std::cout << *it << ' ';
}
std::cout << '\n';
return 0;
}
Output
10 20 30
How It Works
nums.cbegin() gives a read-only iterator even though nums is not const.
*it reads each value in turn.
The loop ends at nums.cend().
Example 2 — Add Numbers with std::accumulate
Algorithms that only read are a good match for cbegin().
C++
#include <array>
#include <iostream>
#include <numeric>
int main() {
std::array<int, 4> nums = {1, 2, 3, 4};
int total = std::accumulate(nums.cbegin(), nums.cend(), 0);
std::cout << "Total: " << total << '\n';
return 0;
}
Output
Total: 10
How It Works
std::accumulate only reads the values, so read-only iterators are enough.
The third argument 0 is the starting sum.
It adds 1 + 2 + 3 + 4 and returns 10.
Example 3 — Jump Ahead from cbegin()
Array iterators support simple math, so you can jump to any element.
Adding 2 moves the iterator two places forward, to index 2.
*it reads the value there, which is 7.
Frequently Asked Questions
It returns a const_iterator that points to the first element of the array. You can read the element but not change it.
On a non-const array, begin() gives an iterator that can change elements, while cbegin() always gives a read-only one. On a const array, both are read-only.
It makes your intent clear and lets the compiler stop accidental writes. It is a good habit when a loop should only read.
Yes. Use cbegin() and cend() together so both iterators have the same type.
Yes. It returns an iterator equal to cend(). The loop body simply never runs.