C++ 如何在std::map<;中找到最小值;标准::字符串,浮点值>;?
我正在尝试获取C++ 如何在std::map<;中找到最小值;标准::字符串,浮点值>;?,c++,algorithm,comparator,stdmap,minimum,C++,Algorithm,Comparator,Stdmap,Minimum,我正在尝试获取std::map中的最小值。我有一个函数,它来自 当我运行这个函数时,我得到一个错误显示 Called object type 'bool (Tool::*)(std::__1::pair<std::__1::basic_string<char>, float>, std::__1::pair<std::__1::basic_string<char>, float>)' is not a function or function po
std::map
中的最小值。我有一个函数,它来自
当我运行这个函数时,我得到一个错误显示
Called object type 'bool (Tool::*)(std::__1::pair<std::__1::basic_string<char>, float>, std::__1::pair<std::__1::basic_string<char>, float>)' is not a function or function pointer
被调用的对象类型“bool(工具::*)(std::\u 1::pair,std::\u 1::pair)”不是函数或函数指针
您提供的比较功能不是一个
应该是
using Pair = std::pair<const std::string, float>; // just a alias type for convenience
struct Tool
{
bool operator()(const Pair& i, const Pair& j)const
/*^^^^^^^^*/ /*^^^*/
{
return (i.second < j.second);
}
};
但是,如果您可以访问C++11或更高版本,只需使用lambda,它将帮助您在调用的行上查看比较函数(二进制谓词)的定义
min = *min_element(direction.begin(), direction.end(),
[](const auto& lhs, const auto& rhs){ return lhs.second < rhs.second;});
min=*min\u元素(direction.begin(),direction.end(),
[](const auto&lhs,const auto&rhs){返回lhs.second
如果您使用的是C++11或更高版本,只需使用lambda而不是成员函数即可。
using Pair = std::pair<const std::string, float>; // just a alias type for convenience
struct Tool
{
bool operator()(const Pair& i, const Pair& j)const
/*^^^^^^^^*/ /*^^^*/
{
return (i.second < j.second);
}
};
min = *min_element(direction.begin(), direction.end(), Tool());
^^^^^^
min = *min_element(direction.begin(), direction.end(),
[](const auto& lhs, const auto& rhs){ return lhs.second < rhs.second;});