Last key in a std::map

2019-04-03 01:33发布

I am looking for the highest key value (a defined by the comparison operator) of a 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)

If not, please advise. I cannot change the data structure.

3条回答
疯言疯语
2楼-- · 2019-04-03 02:06

You can use following method :-

if(!map.empty())
    (--map.end())->first;
查看更多
Viruses.
3楼-- · 2019-04-03 02:21

Yes. Map is a sorted container, the reverse iterator must return the elements in reverse (i.e. decreasing) order of their keys.

[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]

查看更多
对你真心纯属浪费
4楼-- · 2019-04-03 02:21

Yes, but remember to check that map.rbegin() != map.rend().

查看更多
登录 后发表回答