如何在地图中找到最小值?

2022-01-07 00:00:00 dictionary minimum c++ stl stdmap

我有一个 map,我想在地图中找到最小值(右侧).我是这样做的:

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<std::string ,int> i, pair<std::string, int> j) {
  return i.second < j.second;
}
////////////////////////////////////////////////////
std::map<std::string, int> mymap;

mymap["key1"] = 50;
mymap["key2"] = 20;
mymap["key3"] = 100;

std::pair<char, int> min = *min_element(mymap.begin(), mymap.end(), compare); 
std::cout << "min " << min.second<< " " << std::endl;

上面的代码运行良好,我能够得到最小值.但是,当我将这段代码按如下方式放入我的类中时,它似乎不起作用:

The code above works fine and I'm able to get the minimum value. However, when I put this code inside my class as follows, it doesn't seem to work:

int MyClass::getMin(std::map<std::string, int> mymap) {
  std::pair<std::string, int> min = *min_element(mymap.begin(), mymap.end(), 
                                                 (*this).compare);
                                                 // Error probably due to "this".
  return min.second; 
}

bool MyClass::compare(
    std::pair<std::string, int> i, std::pair<std::string, int> j) { 
  return i.second < j.second; 
}

我怎样才能让代码与我的班级一起工作?另外,是否有更好的解决方案不需要编写额外的 compare 函数?

How can I make the code work with my class? Also, is there a better solution which doesn't require writing the additional compare function?

推荐答案

您有几个选择.做到这一点的最佳"方法是使用 函子,这保证是最快的调用:

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<std::string, int> MyPairType;
struct CompareSecond
{
    bool operator()(const MyPairType& left, const MyPairType& right) const
    {
        return left.second < right.second;
    }
};



int MyClass::getMin(std::map<std::string, int> mymap) 
{
  std::pair<std::string, int> min 
      = *min_element(mymap.begin(), mymap.end(), CompareSecond());
  return min.second; 
}

(您也可以将 CompareSecond 类嵌套在 MyClass 中.

(You can also nest the CompareSecond class inside MyClass.

但是,使用您现在拥有的代码,您可以轻松修改它以使其正常工作.只需使函数 static 并使用正确的语法:

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<std::string, int> i, std::pair<std::string, int> j) 
{ 
  return i.second < j.second; 
}

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

相关文章