[英]Why does std::sort work when the comparison function uses greater-than (>), but not greater-than-or-equal (>=)?
On WIN32, Visual Studio 2022. When I define a vector<int>
containing one hundred 0s and sort it with the code below, an exception "invalid comparator" throws.在 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;
});
However, if I use return a > b
, it will execute well.但是,如果我使用
return a > b
,它会执行得很好。 Why is that?这是为什么?
This is just how it is required to work .这正是它需要的工作方式。 You need strict weak ordering .
您需要严格的弱排序。
For the rationale, I believe that the sufficient explanation is that this enables you to determine whether those elements are equal (useful for eg std::set
s).对于基本原理,我认为充分的解释是这使您能够确定这些元素是否相等(例如对
std::set
有用)。 . <=
or >=
can't do that。<=
或>=
不能那样做
<=
or >=
can also do that, but it seems like it was just decided to use <
instead of any other relation. <=
或>=
也可以做到这一点,但似乎只是决定使用<
而不是任何其他关系。 With this decision in mind, standard library facilities are implemented and they heavily rely on it .考虑到这一决定,标准图书馆设施得以实施,他们严重依赖它。
The problem is that the comparator (aka comparing function) that you've provided does not implement a strict-weak-ordering and thus it violates a precondition of std::sort
leading to undefined behavior .问题是您提供的比较器(又名比较函数)没有实现严格的弱排序,因此它违反了导致未定义行为的
std::sort
的先决条件。
comp - comparison function object (ie an object that satisfies the requirements of Compare ) which returns true if the first argument is less than (ie is ordered before) the second.
comp - 比较函数对象(即满足 Compare 要求的对象),如果第一个参数小于(即排在第二个之前)则返回 true。
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 类型的对象的函数调用操作的返回值,当上下文转换为 bool 时,如果调用的第一个参数出现在由该类型引起的严格弱排序关系中的第二个参数之前,则返回 true,否则返回 false除此以外。
This basically means that the comparator function Compare
that we provide should not evaluate to true
for both of the expressions: Compare(x, y)
and Compare(y, x)
where x
and y
are some arguments.这基本上意味着我们提供的比较器函数
Compare
不应该对以下两个表达式求值为true
: Compare(x, y)
和Compare(y, x)
,其中x
和y
是一些参数。 Otherwise, the comparator does not obey the strict-weak-ordering.否则,比较器不服从严格的弱排序。
To solve this you should replace the >=
with >
.要解决此问题,您应该将
>=
替换为>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.