在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:39:53  来源:igfitidea点击:

Getting first value from map in C++

c++map

提问by adir

I'm using mapin C++. Suppose I have 10 values in the mapand 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()->firstto get the key and myMap.begin()->secondto 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 ->firstand ->secondof 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