How can I find the minimum value in a map?

前端 未结 5 1752
夕颜
夕颜 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:16

    You have a few options. The "best" way to do this is with a functor, this is guaranteed to be the fastest to call:

    typedef std::pair MyPairType;
    struct CompareSecond
    {
        bool operator()(const MyPairType& left, const MyPairType& right) const
        {
            return left.second < right.second;
        }
    };
    
    
    
    int MyClass::getMin(std::map mymap) 
    {
      std::pair min 
          = *min_element(mymap.begin(), mymap.end(), CompareSecond());
      return min.second; 
    }
    

    (You can also nest the CompareSecond class inside MyClass.

    With the code you have now, you can easily modify it to work, however. Just make the function static and use the correct syntax:

    static bool 
    MyClass::compare(std::pair i, std::pair j) 
    { 
      return i.second < j.second; 
    }
    
    int MyClass::getMin(std::map mymap) 
    {
      std::pair min = *min_element(mymap.begin(), mymap.end(), 
                                                     &MyClass::compare);
      return min.second; 
    }
    

提交回复
热议问题