将std::vector中的唯一元素插入std::set

inserting unique elements from std::vector to std::set

本文关键字:std 元素 插入 set 唯一 vector      更新时间:2023-10-16

我有一个名为Point的类,用于存储x和y双精度值。我有一个包含重复值的std::vector (Point) s。我正在计算这个向量中唯一项的个数。

我认为因为std::set只有唯一的对象,从vector创建set会给我唯一的值。但我没有得到正确的结果。我重载了相等运算符。但是重复的值仍然被插入到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;
}

你所有的元素都是不同的,因为你:

1)使用指针,因此您必须传递一个自定义比较器,该比较器将指针与Point进行比较,并考虑它们指向的内容。

2)假设std::set使用operator ==operator !=,而实际上它使用operator <

我将有一个Point的集合,而不是Point*。你有理由使用指针而不是对象吗?如果没有,则使用对象。