Getting first value from map in C++

C++Map

C++ Problem Overview


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.

C++ Solutions


Solution 1 - 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.

Solution 2 - C++

As simple as:

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

Solution 3 - C++

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)

Solution 4 - C++

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.

Solution 5 - C++

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionadirView Question on Stackoverflow
Solution 1 - C++BenoitView Answer on Stackoverflow
Solution 2 - C++jweyrichView Answer on Stackoverflow
Solution 3 - C++NimView Answer on Stackoverflow
Solution 4 - C++Marcus GründlerView Answer on Stackoverflow
Solution 5 - C++Oliver CharlesworthView Answer on Stackoverflow