How to write a custom comparator for a QList of pointers?

Viewed 516

I have a QList<MyPoint*> l where MyPoint is a user-defiend class type where I'd like to do:

 QList<MyPoint*> l;
 MyPoint *a = new MyPoint(2, 4);
 MyPoint *b = new MyPoint(4, 8);
 MyPoint *c = new MyPoint(2, 4);
 l << a << b;

then:

l.contains(c); //true

I tried overload == operator as doc says:

This function requires the value type to have an implementation of operator==().

Tried different ways but neither seems to work as expected.

Here's the code I've tried so far:

class MyPoint
{
public:
    int x, y;

    MyPoint(int x, int y)
        : x(x),
          y(y)
    {
    }

    bool operator == (const MyPoint &other) const
    {
        return other.x == this->x && other.y == this->y;
    }

    bool operator == (const MyPoint *other) const
    {
        return true;
    }
};

bool operator == (const MyPoint &a, const MyPoint &b)
{
    return a.x == b.x && a.y == b.y;
}

I tried something like:

bool operator == (const MyPoint *a, const MyPoint *b)
{
    return a.x == b.x && a.y == b.y;
}

But I read this isn't possible... I know (*a == *c) will be true but I'd like to it affect contains() behavior so that it compare using my own comparator.

1 Answers
Related