Last key in a std::map

Viewed 73136

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.

5 Answers

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]

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

One more way -

std::prev(map.end())->first;

Map store the key value pairs in sorted order so we can access the last element by :-

auto it=m.end();
it--;
int element=it->first;
Related