Home > Software engineering >  Why can't the overload operator<() implement the comparison function?
Why can't the overload operator<() implement the comparison function?

Time:11-17

I was looking at this. The author first defined operator<() in my_data and said "everything is normal". After adding a member variable, he said "operator<() does not really implement a comparison operation". I want to know what is the difference between the two and why the former is wrong?


struct my_data
{
    std::string key;
    std::string value;
    //first
    bool operator<(const my_data data)const {           
        return key < data.key;
    }
};
//second
struct Compare
{
    bool operator()(const my_data& l, const my_data& r)
        const {
        return l.key < r.key;
    }
};

from there

CodePudding user response:

With

struct my_data
{
    std::string key;
    std::string value;
    //first
    bool operator<(const my_data data)const {           
        return key < data.key;
    }
};

std::set<my_data> data;

You can use the class with a std::set, but your operator < isn't using all of the object, it is just comparing a single field. That is what the author of the video is complaining about. They take issue that it only compares one field of the object, and not the whole state of the object. By switching to

struct my_data
{
    std::string key;
    std::string value;
};

struct Compare
{
    bool operator()(const my_data& l, const my_data& r)
        const {
        return l.key < r.key;
    }
};

std::set<my_data, Compare> data;

There is no longer a "lying" operator <, but instead a custom comparator that compares just what you want.

  •  Tags:  
  • c
  • Related