我在 C + + 中使用的是 map。假设我在 map中有10个值,我只想要第一个。我怎么才能得到它?
map
谢谢。
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)
begin()
->first
->second
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).
*(myMap.begin())
You could also do myMap.begin()->first to get the key and myMap.begin()->second to get the value.
myMap.begin()->first
myMap.begin()->second
*my_map.begin(). See e.g. http://cplusplus.com/reference/stl/map/begin/.
*my_map.begin()
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.