In C++, std::deque::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 <deque> to use it.
This is a member of std::deque<T>, a double-ended queue. A deque is fast at adding and removing at both ends, and it allows access by index like std::vector. Unlike a vector, its elements are stored in several blocks, not in one contiguous block.
Syntax
Call cbegin with empty brackets. It takes no arguments.
C++
auto it = d.cbegin();
int first = *it;
Call
What it does
d.cbegin()
Returns a read-only iterator to the first element.
*d.cbegin()
Reads the first element. Writing to it is a compile error.
cbegin() always gives a const_iterator, even when the deque itself is not const. begin() only does that for a const deque.
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. You can read the element and move the iterator, but you cannot assign to the element.
Empty deque
For an empty deque, cbegin() equals cend().
C++ Examples
Example 1 — Loop with cbegin() and cend()
Print every element without any chance of changing it.
C++
#include <deque>
#include <iostream>
int main() {
std::deque<int> d = {3, 6, 9};
for (auto it = d.cbegin(); it != d.cend(); ++it) {
std::cout << *it << ' ';
}
std::cout << '\n';
return 0;
}
Output
3 6 9
How It Works
d.cbegin() gives a const_iterator to the first element, 3.
Inside the loop, *it can only be read. A line such as *it = 0; would not compile.
The loop stops when the iterator reaches d.cend().
Example 2 — Jump Ahead with a Const Iterator
A deque iterator is random-access, so you can add a number to it.