Getting first value from map in C++

A map will not keep insertion order. Use *(myMap.begin()) to get the value of the first pair (the one with the smallest key when ordered).

You could also do myMap.begin()->first to get the key and myMap.begin()->second to get the value.


As simple as:

your_map.begin()->first // key
your_map.begin()->second // value

begin() returns the first pair, (precisely, an iterator to the first pair, and you can access the key/value as ->first and ->second of that iterator)


You can use the iterator that is returned by the begin() method of the map template:

std::map<K,V> myMap;
std::pair<K,V> firstEntry = *myMap.begin()

But remember that the std::map container stores its content in an ordered way. So the first entry is not always the first entry that has been added.


*my_map.begin(). See e.g. http://cplusplus.com/reference/stl/map/begin/.