I have a map
and I want to find the minimum value (right-hand side) in the map. Here is how I did it:
bool compare(std::pair
As mentioned in Jonathan Geisler's comment on Timmmm's answer, C++14 allows lambda function parameters to be declared with the auto
type specifier. As a result, you can shorten Timmmm's lambda-based min_element line (and improve its readability) as follows:
auto it = std::min_element(std::begin(mymap), std::end(mymap),
[](const auto& l, const auto& r) { return l.second < r.second; });
Note 1: If you put this line into your MyClass::getMin()
function, you have to return it->second
. However, to account for an empty map, you should adapt the return
line as follows (or similar):
return it == mymap.end() ? -1 : it->second;
Note 2: As also mentioned by Lance Diduck, you should be passing the map by const
reference to your getMin()
function. The way you did it, you are creating an unnecessary copy of the whole map.
Code on Ideone