C++ std::map 中的最后一个键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/289715/
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
Last key in a std::map
提问by peterchen
I am looking for the highest key value (a defined by the comparison operator) of a std::map.
我正在寻找 std::map 的最高键值(由比较运算符定义)。
Is this guaranteed to be
这是否保证是
map.rbegin()->first
?
?
(I am a bit shaky on reverse iterators, and how much freedom there is in the implementation of std::map)
(我对反向迭代器有点不稳定,在 std::map 的实现中有多少自由度)
If not, please advise. I cannot change the data structure.
如果没有,请指教。我无法更改数据结构。
回答by Steve Jessop
Yes. Map is a sorted container, the reverse iterator must return the elements in reverse (i.e. decreasing) order of their keys.
是的。Map 是一个已排序的容器,反向迭代器必须以它们的键的反向(即降序)顺序返回元素。
[Edit: as Charles Bailey points out in his answer, your code gives the greatest key if it exists- i.e. if the map is non-empty]
[编辑:正如查尔斯·贝利 (Charles Bailey) 在他的回答中指出的那样,如果存在,您的代码会给出最大的键- 即如果地图不为空]
回答by CB Bailey
Yes, but remember to check that map.rbegin() != map.rend()
.
是的,但记得检查一下map.rbegin() != map.rend()
。
回答by birubisht
You can use following method :-
您可以使用以下方法:-
if(!map.empty())
(--map.end())->first;