How can I find the minimum value in a map?(如何在地图中找到最小值?)
问题描述
我有一个 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;
}
这篇关于如何在地图中找到最小值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在地图中找到最小值?


基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09