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?
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?
As std::map is assosiative array one can easily find biggest or smallest key very easily. By defualt compare function is less(<) operator so biggest key will be last element in map. Similarly if someone has different requirement anyone can modify compare function while declaring map.
std::map< key, Value, compare< key,Value > >
By default compare=std::less
The end:
Maps (and sets) are sorted, so the first element is the smallest, and the last element is the largest. By default maps use
std::less
, but you can switch the comparer and this would of course change the position of the largest element. (For example, usingstd::greater
would place it atbegin()
.Keep in mind
rbegin
returns an iterator. To get the actual key, usem.rbegin()->first
. You might wrap it up into a function for clarity, though I"m not sure if it's worth it:The entries in a std::map are sorted, so for a std::map m (assuming
m.empty()
is false), you can get the biggest key easily:(--m.end())->first