在 WIN32 上,Visual Studio 2022。当我定义 vector<int>
包含一百个 0 并使用下面的代码对其进行排序,抛出异常“无效比较器”。
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 .您需要strict weak ordering .
对于基本原理,我认为充分的解释是,这使您能够确定这些元素是否相等(例如对 std::set
有用)。 。<=
或 >=
不能这样做
<=
或 >=
也可以这样做,但似乎刚刚决定使用 <
而不是任何其他关系。考虑到这一决定,标准库设施得以实现,它们heavily rely on it .
关于c++ - 为什么 std::sort 在比较函数使用大于 (>) 而不是大于或等于 (>=) 时起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71977913/