In C++11, std::unordered_map::cbegin() returns a read-only iterator (a const_iterator) to the first pair of the unordered_map. The first pair is the one with the first pair in iteration order.
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 <unordered_map> to use it.
This is a member of std::unordered_map<Key, T>, a hash table of key and value pairs. Each key is unique. Find, insert, and erase are usually average constant time. Unlike std::map, keys are not sorted and iteration order is unspecified. 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 unordered_map itself is not const.
cbegin() says in your code that the loop will not change the unordered_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
Show that cbegin is valid on a non-empty map and that values can still be read by key.