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
  • 45
  • 1
  • 3
  • 10
  • 1
    Your `operator<` does not define a [*Strict Weak Ordering*](https://www.sgi.com/tech/stl/StrictWeakOrdering.html). – BoBTFish May 06 '16 at 07:59
  • You are correct, when I initialize points with Point={0,0} and int = 1; I receive that {1,1} is not a key whereas {0,1} is.. how do I fix that?. Edit: @BoBTFish hey I missed your link, now I'm checking that out – Jayn May 06 '16 at 08:01
  • 1
    [This question has answers for 3 points](http://stackoverflow.com/q/979759/1171191). – BoBTFish May 06 '16 at 08:02
  • @BoBTFish I've just updated according to the first link, and it works! thank you very much Bob – Jayn May 06 '16 at 08:04
  • Also, the `typedef struct Point {...} Point;` construction is only relevant in C, not C++. – BoBTFish May 06 '16 at 08:07
  • @BoBTFish Then what is the better option? class of Point? – Jayn May 06 '16 at 08:18
  • Just `struct Point {...};` is fine. The only difference between `struct` and `class` is `public`/`private` by default respectively. – BoBTFish May 06 '16 at 08:20
  • @BoBTFish uh ok, thanks Bob – Jayn May 06 '16 at 08:22

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,906
  • 23
  • 39