73

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.

KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
peterchen
  • 40,917
  • 20
  • 104
  • 186

5 Answers5

72

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
  • 273,490
  • 39
  • 460
  • 699
38

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

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
18

You can use following method :-

if(!map.empty())
    (--map.end())->first;
birubisht
  • 890
  • 8
  • 16
  • 2
    This is not guaranteed to work. `std::prev(map.end())->first` is safer. – Kai Petzke Feb 05 '21 at 17:07
  • @KaiPetzke yes that is why I checked the map first. what else can go wrong here please elaborate. thanks – birubisht Jun 23 '21 at 08:17
  • 1
    The problem is, that the C++ standard does not require, that you can apply the `--` operator to the rvalue `map.end()`. For further explanation, see the notes on https://en.cppreference.com/w/cpp/iterator/prev – Kai Petzke Jun 28 '21 at 20:07
  • @KaiPetzke That's a good point. Then what's the difference between `std::prev(map.end())->first` and `map.rbegin()->first`? They seem pretty much the same. – starriet Sep 23 '22 at 15:21
  • 1
    @starriet There is no difference between the two variants you are asking about. Because @birubisht introduced the non-portable `(--map.end())`, I recommended to use the portable `std::prev(map.end())` instead. `map.rbegin()` yields an iterator to exactly the same element. – Kai Petzke Sep 24 '22 at 19:11
16

One more way -

std::prev(map.end())->first;
Alam
  • 1,536
  • 15
  • 26
1

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;