[c++] Getting first value from map in C++

I'm using map in C++. Suppose I have 10 values in the map and I want only the first one. How do I get it?

Thanks.

This question is related to c++ map

The answer is


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)


As simple as:

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

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.