在 C++ 中从地图中获取第一个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4826404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting first value from map in C++
提问by adir
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?
我map
在 C++ 中使用。假设我有 10 个值map
,我只想要第一个。我如何得到它?
Thanks.
谢谢。
回答by Benoit
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
获取值。
回答by jweyrich
As simple as:
就这么简单:
your_map.begin()->first // key
your_map.begin()->second // value
回答by Nim
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
该迭代的)
回答by Marcus Gründler
You can use the iterator that is returned by the begin() method of the map template:
您可以使用地图模板的 begin() 方法返回的迭代器:
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.
但请记住, std::map 容器以有序的方式存储其内容。所以第一个条目并不总是被添加的第一个条目。
回答by Oliver Charlesworth
*my_map.begin()
. See e.g. http://cplusplus.com/reference/stl/map/begin/.
*my_map.begin()
. 参见例如http://cplusplus.com/reference/stl/map/begin/。