Point
x と y の double 値を格納するために使用される というクラスがあります。重複する値を含むstd::vector
ofがあります。Point
このベクター内の一意のアイテムの数を数えようとしています。
std::set
ユニークなオブジェクトのみを作成するとset
、vector
ユニークな値が得られると思いました。しかし、私は正しい結果を得ていません。等価演算子をオーバーロードしました。しかし、それでも重複した値が に挿入されます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;
}