gpt4 book ai didi

c++ - std::sort - 是否传递了错误的比较器未定义行为?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:23:42 27 4
gpt4 key购买 nike

考虑这段代码:

std::sort(vec.begin(), vec.end(),
[](const Foo& lhs, const Foo& rhs) { return !(lhs < rhs); }
);

如果 lhs == rhs,lambda(lhs, rhs) 和 lambda(rhs, lhs) 都将返回 true,这违反了提供严格弱排序的要求。但是,标准是否明确将传递此类比较器标记为未定义行为?

最佳答案

警告:接下来是极端的语言律师。

the most recent draft of the standard 的措辞在[alg.sorting]p3 中是这样写的:

For all algorithms that take Compare, there is a version that uses operator< instead. That is, comp(*i, *j) != false defaults to *i < *j != false. For algorithms other than those described in 25.4.3, comp shall induce a strict weak ordering on the values.

通过使用“应”一词,标准是 implicitly stating that violating it leads to undefined behavior

这是否要求给定函数对所有可能值或仅对给定算法的值施加 SWO,标准中并不清楚。但是,由于限制是在谈论那些特定算法的段落中陈述的,因此假设它指的是提供给算法的值的范围并不是不合理的。

否则,由于 NaN,默认的 operator< 无法为 float 强加 SWO。

关于c++ - std::sort - 是否传递了错误的比较器未定义行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34834125/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com