Last key in a std::map

C++IteratorStdmap

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

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]

Solution 2 - C++

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

Solution 3 - C++

You can use following method :-

if(!map.empty())
    (--map.end())->first;

Solution 4 - C++

One more way -

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

Solution 5 - C++

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpeterchenView Question on Stackoverflow
Solution 1 - C++Steve JessopView Answer on Stackoverflow
Solution 2 - C++CB BaileyView Answer on Stackoverflow
Solution 3 - C++birubishtView Answer on Stackoverflow
Solution 4 - C++AlamView Answer on Stackoverflow
Solution 5 - C++kuldeep singhView Answer on Stackoverflow