views:

448

answers:

2

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.

+8  A: 

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]

Steve Jessop
+6  A: 

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

Charles Bailey
map.size()>0 should do it, too, right?
peterchen
!map.empty() is even clearer.
dalle
They are all equivalent checks.
Charles Bailey
map::size() *could* be O(N)...
Andreas Magnusson
... while .empty() is guaranteed to be O(1). (just to clarify what Andreas said)
Thomas