-3

I am trying to get the minimum value in a std::map. I have a function which is from Finding minimum value in a map

#import tool.mm
std::map<std::string, float> direction;
std::pair<std::string, float> min;

direction["up"] = 50.0;
direction["down"] = 20.0;
direction["right"] = 100.0;
direction["left"] = 200.0;

min = *min_element(direction.begin(), direction.end(), &Tool::compare);

This is what Tool class looks like:

//tool.mm
class Tool 
{
public:
    bool compare(std::pair<std::string, float> i, std::pair<std::string, float> j) {
        return (i.second < j.second);
    }
};

When I run this function I get an error showing

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
JeJo
  • 30,635
  • 6
  • 49
  • 88
Cristian
  • 495
  • 2
  • 9
  • 35

1 Answers1

3

The compare function what you provided is not a functor.

It supposed to be

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);
    }
};

and you should be calling it like

min = *min_element(direction.begin(), direction.end(), Tool());
                                                       ^^^^^^

However, if you have access to C++11 or later versions, just use lambda which will help you to see the definition of compare function(binary predicate) on the line where you call.

min = *min_element(direction.begin(), direction.end(), 
                   [](const auto& lhs, const auto& rhs){ return lhs.second < rhs.second;});
JeJo
  • 30,635
  • 6
  • 49
  • 88