Getting first value from map in C++
C++MapC++ 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++
*my_map.begin()
. See e.g. http://cplusplus.com/reference/stl/map/begin/.