C++ How to find the biggest key in a std::map?

Viewed 49257

At the moment my solution is to iterate through the map to solve this.

I see there is a upper_bound method which can make this loop faster, but is there a quicker or more succinct way?

5 Answers

Since the map is just an AVL tree then, it's sorted -in an ascending order-. So, the element with largest key is the last element and you can obtain it using one of the following two methods:

1.

    largestElement = (myMap.rbegin())-> first; // rbegin(): returns an iterator pointing to the last element
    largestElement = (--myMap.end())->first; // end(): returns an iterator pointing to the theortical element following the last element 

Since you're not using unordered_map, your keys should be in order. Depending upon what you want to do with an iterator, you have two options:

  1. If you want a forwards-iterator then you can use std::prev(myMap.end()). Note that --myMap.end() isn't guaranteed to work in all scenarios, so I'd usually avoid it.
  2. If you want to iterate in reverse then use myMap.rbegin()
Related