在 C + + 中从 map 获取第一个值

我在 C + + 中使用的是 map。假设我在 map中有10个值,我只想要第一个。我怎么才能得到它?

谢谢。

144006 次浏览

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)

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

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.