1

Right now I have a class item

   class Item{
        public:

            short p;        //profit
            short w;        //weight
            bool *x;        //pointer to original solution variable
            void set_values (short p, short w, bool *x);

    };

and I need to compare two different instances so that it checks the values of each one and returns either true/false

 if (Item a < Item b){
       //do something
 }

How can I do that? I've been reading cppreference but I don't really understand how to do it.

xaxxon
  • 19,189
  • 5
  • 50
  • 80
Carlos Ramírez
  • 121
  • 1
  • 3
  • 9

3 Answers3

6

Very simply,

bool Item::operator<(const Item& other) const {
    // Compare profits
    return this->p < other.p;
}
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
2

To compare both the left hand side p and w with the right hand side p and w use the following code:

class MyClass
{
public:
    short p;
    short w;
    friend bool operator<(const MyClass& lhs, const MyClass& rhs)
    {
        return lhs.p < rhs.p && lhs.w < rhs.w;
    }
};
Ron
  • 14,674
  • 4
  • 34
  • 47
1

For example, if you want to compare p, the code should look like this:

class Item {
private:
...
public:
    friend bool operator < (const Item& lhs, const Item& rhs) {
        return lhs.p < rhs.p;
    }
};
Jiahao Cai
  • 1,222
  • 1
  • 11
  • 25