C++ unordered_map begin() Function
Example
Loop through an unordered map with an iterator, and add up all the ages:
unordered_map<string, int> people = {{"John", 32}, {"Adele", 45}, {"Bo", 29}};
int total = 0;
for (auto it = people.begin(); it != people.end(); ++it) {
total += it->second;
}
cout << "Total age: " << total;
Definition and Usage
The begin() function returns an iterator (a pointer-like object that points to an element) to the first element of an unordered map.
The elements are not sorted, so the first element can be any of them. This is why begin() is mostly used together with end(), to loop through all the elements. Use it->first to get the key and it->second to get the value.
The begin function is defined in the <unordered_map> header file.
Tip: The auto keyword lets the compiler find the type of the iterator for you. Learn more in the Iterators chapter.
Syntax
unordered_map.begin()
Parameter Values
None.
Technical Details
| Returns: | An iterator pointing to the first element of the unordered map. If the unordered map is empty, it is equal to unordered_map.end(). |
|---|
Related Pages
Read more about unordered maps in our Unordered Map Tutorial.