删除重复项的有效方法

时间:2014-03-03 19:33:26

标签: c++ std

在此帖子中回答“What's the most efficient way to erase duplicates and sort a vector?”。我写了下面的代码,但是我抱怨no match for ‘operator<’ (operand types are ‘const connector’ and ‘const connector’) blahblah ......

connector是我自己写的一个类,它基本上是一个有两个几何点的线。 uniqCntrs是一个std :: vector。它有100%的重复,这意味着每个元素都有重复,uniqCntrs的大小非常大。我的代码有什么问题,以及如何处理这种情况?

std::set<connector> uniqCntrsSet;
for(unsigned int i = 0; i < uniqCntrs.size(); ++i )
{
    uniqCntrsSet.insert(uniqCntrs[i]);
}
uniqCntrs.assign(uniqCntrsSet.begin(), uniqCntrsSet.end());

编辑:

我不知道如何为我的连接器类定义<运算符。我的意思是说一条线比另一条线在物理上毫无意义。

2 个答案:

答案 0 :(得分:5)

来自cppreference

  

std::set是一个关联容器,包含一组有序的Key类型的唯一对象。使用密钥比较函数Compare进行排序。

std::set的第二个模板参数Compare默认为std::less,默认情况下会将对象与operator<进行比较。要解决此问题,您只需为operator<类型(Key)定义connector

答案 1 :(得分:3)

实际上,operator<仅用于有效地排序std::set使用的地图。它没有任何意义。唯一的要求是运算符满足strict weak ordering的标准数学定义。

看看这一点的例子:

class Point
{
public:
    Point(int x, int y) : x(x), y(y) {
    }

public:
    bool operator==(const Point &other) const {
        return x==other.x && y==other.y;
    }
    bool operator!=(const Point &other) const {
        return !operator==(other);
    }
    bool operator<(const Point &other) const {
        if (x==other.x) {
            return y<other.y;
        } else {
            return x<other.x;
        }
    }

private:
    int x;
    int y;
};