2

Pointx と y の double 値を格納するために使用される というクラスがあります。重複する値を含むstd::vectorofがあります。Pointこのベクター内の一意のアイテムの数を数えようとしています。

std::setユニークなオブジェクトのみを作成するとsetvectorユニークな値が得られると思いました。しかし、私は正しい結果を得ていません。等価演算子をオーバーロードしました。しかし、それでも重複した値が に挿入されますset

現在の結果は以下のようなものです..

10,10 repetitions - 1
10,10 repetitions - 1
20,20 repetitions - 1
20,20 repetitions - 1

私は期待している...

10,10 repetitions - 2
20,20 repetitions - 2

私が間違っている手がかりはありますか?完全なコードは以下のとおりです。

Point.h ファイル

#ifndef POINT_H
#define POINT_H
class Point
{
public:
    Point(double x, double y);
    double getX();
    double getY();

    Point(const Point &other);

    bool operator == (const Point& p );
    bool operator != (const Point& p );

private:
    double _x;
    double _y;
};
#endif // POINT_H

Point.cpp ファイル

#include "point.h"

Point::Point(double x, double y)
{
    _x = x;
    _y = y;
}

Point::Point(const Point &other)
{
    _x = other._x;
    _y = other._y;
}

double Point::getX()
{
    return _x;
}

double Point::getY()
{
    return _y;
}

bool Point::operator == ( const Point& p )
{
    return ( (_x  == p._x ) && (_y == p._y));
}

bool Point::operator != ( const Point& p )
{
    return !((*this) == p );
}

main.cpp ファイル

#include <iostream>
#include <vector>
#include <set>
#include "Point.h"
using namespace std;

int main()
{
    std::vector <Point*> pointsVector;
    pointsVector.push_back(new Point(10,10));
    pointsVector.push_back(new Point(10,10));
    pointsVector.push_back(new Point(20,20));
    pointsVector.push_back(new Point(20,20));


    std::set<Point*> uniqueSet( pointsVector.begin(), pointsVector.end() );

    std::set<Point*>::iterator it;
    for (it = uniqueSet.begin(); it != uniqueSet.end(); ++it)
    {
        Point* f = *it; // Note the "*" here
        int result = std::count( pointsVector.begin(), pointsVector.end(), f );
        cout << f->getX() << "," << f->getY() << " repetitions - " << result << endl;
    }

    return 0;
}
4

1 に答える 1

4

次の理由により、すべての要素が異なります。

Point1) ポインターを使用するため、ポインターが何を指すかを考慮してポインターを比較するカスタム コンパレーターを渡す必要があります。

std::set2)使用を想定しているoperator ==、またはoperator !=実際に使用している場合operator <

Pointの代わりに のコレクションがありPoint*ます。オブジェクトの代わりにポインターを使用する理由はありますか? そうでない場合は、オブジェクトを使用します。

于 2012-12-27T10:06:44.820 に答える