2016-05-06 3 views
0

ポイントは、フォームの構造体である:C++の構造体のマップで作業

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; 

と私が使用している:、マップは{{0,0}で初期化され

map<Point,int> points; 

を1 }。プログラムはpoints.count(p)を使用して、ポイントpがポイントマップのキーであるかどうかを確認しました。
問題があり、プログラムは常にyesを返します。地図にない点についても私はpがポイントのキーでない場合、points.count(== 1)を得ています。
また、points.find(p)を使用して、受信したポイントが本当に== 0であるかどうかを確認するためにイテレータを取得する場合、全く異なるポイントへの参照を取得しています。
どのように問題を解決する?

+1

あなた '演算子<' [* *厳格な弱順序]定義していません(HTTPS ://www.sgi.com/tech/stl/StrictWeakOrdering.html)。 – BoBTFish

+0

Point = {0,0}とint = 1の点を初期化すると正しいですか。私は{1,1}がキーではないのに対し、{0,1}はそれです。私はそれをどのように修正するのですか?編集:@BoBTFishちょっと、私はあなたのリンクを逃した、今私はそれをチェックしている – Jayn

+1

[この質問は3点の答えがある](http://stackoverflow.com/q/979759/1171191)。 – BoBTFish

答えて

1

operator<()が間違って定義されています。私がa=Point{0,1}b=Point{1,1}を持っているとします。そして、a<bでもb<aでもa==bでも真であり、オペレータは可能なポイントのセットを注文しません。これを修正するためには、寸法のものを作る必要がある(たとえばx)は、あなたの比較において「メジャー」の寸法:

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