0

Point is a struct of the form:

typedef struct Point {
    int x;
    int y;
    bool operator<(const Point &other) const
    {
        return ((this->x < other.x) && (this->y < other.y));
    };
    bool operator!=(const Point &other) const
    {
        return ((this->x != other.x) || (this->y != other.y));
    }
    bool operator==(const Point &other) const
    {
        return ((this->x == other.x) && (this->y == other.y));
    }
} Point;

and I'm using:

map<Point,int> points;

the map is initialized with {{0,0},1}. and the program used points.count(p) to check whether the point p is a key in the points map.
There's a problem and the program always returns yes! even for points not in the map. I mean if p is not a key in points, I'm getting points.count(p)==1 (and not 0).
Also, when using points.find(p) to get the iterator to check whether the received point is really ==0 (it is not), I'm getting a reference to a totally different point..
Any idea how to fix the problem?

Jayn
  • 35
  • 1
  • 3
  • 9

1 Answers1

1

Your operator<() is badly defined. Suppose I have a=Point{0,1} and b=Point{1,1}. Then neither a<b nor b<a nor a==b is true, which makes the operator not an ordering on the set of possible points. In order to correct this you need to make one of the dimensions (say x) the 'major' dimension in your comparison:

bool operator<(const Point &other) const
{
    return ((this->x < other.x) || 
             ((this->x == other.x) && (this->y < other.y));
};
Smeeheey
  • 9,582
  • 18
  • 37