我不太明白std::is_sorted
算法及其默认行为。如果我们查看 cppreference , 它表示默认情况下 std::is_sorted
使用 <
运算符(operator)。相反,我发现使用 <=
会很自然。但我的问题是,对于以下数字列表:
1 2 3 3 4 5
它将返回 true
, 即使3 < 3
应该是 false
.这怎么可能?
编辑:它似乎比我想象的更糟糕,因为通过了 std::less_equal<int>
在这种情况下将返回 false...当我传递比较器函数时应用的条件是什么?
最佳答案
根据 25.4/5:
A sequence is sorted with respect to a comparator
comp
if for any iteratori
pointing to the sequence and any non-negative integern
such thati + n
is a valid iterator pointing to an element of the sequence,comp(*(i + n), *i) == false
.
所以,对于
1 2 3 3 4 5
std::less<int>()(*(i + n), *i)
将返回 false
对于所有 n
, 而 std::less_equal
将返回 true
对于案例 3 3
.
关于c++ - std::is_sorted 和 strictly less 比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17769114/