You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何lambda始终返回true时std::is_sorted返回false致断言崩溃?

为什么传入始终返回true的lambda时std::is_sorted会返回false?

核心原因:std::is_sorted对比较谓词的语义要求

std::is_sorted的自定义比较谓词需要满足严格弱序,并且语义明确:comp(a, b)返回true,表示a应该排在b的前面(符合排序后的预期顺序)。

而std::is_sorted的判断逻辑是:遍历序列中每一对相邻元素(前一个为prev,后一个为next),只要存在任意一对满足comp(next, prev) == true,就会判定序列未按要求排序,返回false;只有所有相邻对都满足comp(next, prev) == false时,才返回true。

对应代码的问题分析

看这段代码:

#include <vector>
#include <cassert>
#include <algorithm>

int main() {
    std::vector<int> vt = {1,2,3,4};
    assert(std::is_sorted(vt.begin(), vt.end(), [](const auto& a, const auto& b){ return true;}));
}

这里的lambda无论传入什么参数都返回true,意味着对于序列里的任意相邻元素(比如1和2),comp(2, 1)也会返回true——按照谓词的语义,这表示2应该排在1前面,但实际序列里1在2前面,完全矛盾。

因此std::is_sorted会判定序列不符合排序要求,返回false,触发assert导致程序崩溃。

内容的提问来源于stack exchange,提问作者zizeca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 19:29:54