首页 > 解决方案 > 比较器的两种实现之间的区别

问题描述

我的代码中有一个名为 edge 的对象类,它需要定义运算符 < 来对对象进行排序。我以两种方式定义它,而另一种工作方式只是给出运行时错误(分段错误)。我想知道这东西是怎么工作的?我正在使用 std:: sort 来达到我的目的。

struct edge{
    int u;
    int v;
    int w;

    edge(int a, int b, int c) : u(a), v(b), w(c){}

    bool operator<(const edge &other) const{
        return (w <= other.w);
    }
};

上面的代码给出了运行时错误。

struct edge{
    int u;
    int v;
    int w;

    edge(int a, int b, int c) : u(a), v(b), w(c){}

    bool operator<(const edge &other) const{
        return (w < other.w);
    }
};

上面的代码工作正常。

标签: c++sortingcomparator

解决方案


operator<如果第一个参数小于第二个参数,则应返回 true,否则返回 false。排序算法依赖于这种行为,如果不是真的,可能会崩溃。

显然问题在于

bool operator<(const edge &other) const{
    return (w <= other.w);
}

是如果两条边相等则返回true,这违反了上述规则,这意味着排序算法将不起作用。


推荐阅读