问题描述
我有一张地图,我想在地图中找到最小值(右侧)。现在这里是我怎么做了
I have a map and I want to find the minimum value (right hand side) in the map. Right now 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;
这很好,我可以得到最小值的问题是,在我的类中似乎不工作
This works fine and I'm able to get the minimum value the problem is when I put this code inside my class 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;
}
还有一个更好的解决方案,不涉及写入额外的比较
函数
Also is there a better solution not involving to 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
class in 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;
}
这篇关于在地图中查找最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!