In C++11, std::map::cbegin() returns a read-only iterator (a const_iterator) to the first pair of the map. The first pair is the one with the smallest key.
The c stands for const. Through this iterator you can read it->first and it->second, but the compiler stops you from changing them. Include <map> to use it.
This is a member of std::map<Key, T>, a sorted container of key and value pairs. Each key is unique and the pairs are always kept in key order, so a map can find, insert, and erase a key in logarithmic time. Read a value with at() or find(). The m[key] operator also works, but it adds a default value when the key is missing.
Syntax
Call cbegin with empty brackets. Pair it with cend().
C++
auto it = m.cbegin(); // const_iterator
for (auto p = m.cbegin(); p != m.cend(); ++p) {
std::cout << p->first; // read only
}
Call
What it does
m.cbegin()
Returns a const_iterator to the first pair, even when the map itself is not const.
cbegin() says in your code that the loop will not change the map. On a const map, begin() already returns a const_iterator, so both give the same type.
Library declarations
C++
const_iterator cbegin() const noexcept; // C++11
Parameters
Parameter
Description
None
cbegin() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
const_iterator
A read-only iterator to the first pair. It equals cend() for an empty map.
C++ Examples
Example 1 — cbegin() Reads Without Changing
Get a read-only iterator to the first pair and print it.