自定义比较器 - 将"<="保存交换"<"?

icy*_*icy 6 c++

假设我有一个自定义的多标准比较器,尽管多部分可能并不重要.为了简单起见,我们假设我们正在排序由3个表示坐标的双精度组成的数组.

我知道go-to比较运算符是"<",但我有这种唠叨的感觉,如果所有部分都相等,"<="可能会保存交换.分拣机(例如std :: sort)是否会,"嘿,如果比较器返回false,我正在交换你!",或者这是不正确的假设?谢谢.

// Compare based on X, then Y, then Z
bool PointComparer(const array<double,3>& a, const array<double,3>& b)
{
    if (a[0] < b[0]) return true;
    if (a[0] > b[0]) return false;

    if (a[1] < b[1]) return true;
    if (a[1] > b[1]) return false;

    return a[2] < b[2];  // If instead was a[2] <= b[2], would it save a swap in equal case?
}
// Later sort a collection of these arrays
Run Code Online (Sandbox Code Playgroud)

Sla*_*ica 9

您不能使用<=std::sort()和类似的标准算法,因为它不符合比较概念,这需要严格的弱序,违反这个条件:

对于S中的所有x,不是x <x(反射性)的情况.

所以使用这个运算符会导致UB,如果它会阻止交换,那就毫无意义.