为什么当比较函数使用大于 (>) 而不是大于或等于 (>=) 时 std::sort 起作用?

Why does std::sort work when the comparison function uses greater-than (>), but not greater-than-or-equal (>=)?

在 WIN32 上,Visual Studio 2022。当我定义一个包含一百个 0 的 vector<int> 并使用下面的代码对其进行排序时,抛出异常“无效比较器”。

vector<int> v(100, 0);
sort(v.begin(), v.end(), [](const int& a, const int& b)
    {
        return a >= b;
    });

但是,如果我使用return a > b,它会执行得很好。这是为什么?

This is just how it is required to work. You need strict weak ordering.

对于基本原理,我认为充分的解释是这使您能够确定这些元素是否相等(例如对 std::sets 有用)。 <=>= 做不到 .

<=>= 也可以做到这一点,但似乎只是决定使用 < 而不是任何其他关系。考虑到这一决定,实施了标准图书馆设施,并且 .

问题是您提供的比较器(又名比较函数)没有实现 strict-weak-ordering 因此它 违反了 std::sort 的先决条件,导致 未定义的行为 .

来自 std::sort:

comp - comparison function object (i.e. an object that satisfies the requirements of Compare) which returns ​true if the first argument is less than (i.e. is ordered before) the second.

来自 Compare:

The return value of the function call operation applied to an object of a type satisfying Compare, when contextually converted to bool, yields true if the first argument of the call appears before the second in the strict weak ordering relation induced by this type, and false otherwise.

这基本上意味着我们提供的比较函数 Compare 不应为以下两个表达式求得 trueCompare(x, y)Compare(y, x),其中 xy 是一些参数。否则,比较器不服从 strict-weak-ordering.

要解决此问题,您应该将 >= 替换为 >