C++ map begin() Function
Example
Get the first element of a map:
map<string, int> people = {{"John", 32}, {"Adele", 45}, {"Bo", 29}};
auto it = people.begin();
cout << it->first << " is: " << it->second;
Definition and Usage
The begin() function returns an iterator (a pointer-like object that points to an element) to the first element of a map.
Map elements are sorted by key, so the first element is the one with the smallest key. In the example, "Adele" comes first in alphabetical order. Use it->first to get the key and it->second to get the value.
The begin function is defined in the <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
map.begin()
Parameter Values
None.
Technical Details
| Returns: | An iterator pointing to the first element of the map. If the map is empty, it is equal to map.end(). |
|---|
Related Pages
Read more about maps in our Maps Tutorial.