我有一个名为 的类Point
,用于存储 x 和 y 双精度值。我有一个包含重复值的std::vector
of s。Point
我正在尝试计算此向量中唯一项目的数量。
我想既然std::set
只有独特的对象,创建一个set
fromvector
会给我独特的价值。但我没有得到正确的结果。我已经重载了相等运算符。但仍然重复的值被插入到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
任何线索我错了?完整代码如下。
点.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
点.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;
}