How can I find the minimum value in a map?

前端 未结 5 1733
夕颜
夕颜 2020-12-05 23:49

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

        
5条回答
  •  有刺的猬
    2020-12-06 00:37

    C++14

    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

提交回复
热议问题