std::is_sorted只接受迭代器范围而非容器对象,对空或单元素容器恒返回true,支持前向迭代器容器,默认检测非降序(允许相等),可传自定义比较函数。

std::is_sorted 要求传入迭代器范围,不是容器本身
std::is_sorted 不接收 std::vector 或 std::list 这类容器对象,只认一对迭代器。直接传容器会编译失败,报错类似:no matching function for call to 'is_sorted'。
正确用法是传 begin() 和 end():
std::vector<int> v = {1, 2, 3, 4, 5};
bool sorted = std::is_sorted(v.begin(), v.end()); // true</int>
- 对空容器或单元素容器,
std::is_sorted恒返回true - 支持所有提供前向迭代器的容器(
std::vector、std::deque、std::array、std::list等) - 不支持
std::forward_list的end()配合使用(因其迭代器不满足必要比较要求),实际中基本不用它配is_sorted
默认按 operator 升序判断,自定义比较要显式传入
如果不指定比较函数,std::is_sorted 内部用 *(i+1) 判断是否“未升序”,即只要有一处违反 <code> 就返回 <code>false。这意味着它检测的是严格升序(不允许相等)?不完全是——它检查的是“非降序”:允许相邻相等,但不允许逆序。
例如:{1, 2, 2, 3} 是合法的,返回 true;而 {1, 3, 2} 返回 false。
若需按其他规则判断(如降序、忽略大小写字符串、或自定义结构体字段):
组合式C++代码评审方案,融合静态分析、AI推理、多轮迭代评审和C++专项检查,适用于PR审查、增量代码审查、全项目评审和代码质量评分,触发词包括review cpp、cpp代码评审、C++review、代码审查。
std::vector<:string> words = {"apple", "Banana", "cherry"};
// 按字典序升序(区分大小写)
bool asc = std::is_sorted(words.begin(), words.end());
// 忽略大小写升序
bool iasc = std::is_sorted(words.begin(), words.end(),
[](const std::string& a, const std::string& b) {
return std::lexicographical_compare(
a.begin(), a.end(), b.begin(), b.end(),
[](char x, char y) { return std::tolower(x) <h3>注意 <code>std::is_sorted</code> 的时间复杂度和短路行为</h3>
<p>它从左到右逐对比较,一旦发现 <code>*(i+1) 成立(即后项“小于”前项),立刻返回 <code>false</code>,不会继续遍历。最好情况 O(1),最坏情况 O(n)。</code></p>
<ul>
<li>对已排序的大容器,性能开销接近完整遍历</li>
<li>对明显乱序的容器(如首两个元素就逆序),几乎瞬间返回</li>
<li>没有“部分校验”模式:不能跳过某些位置,也不能只查前 N 个元素(除非手动截断迭代器范围)</li>
<li>不修改原容器,纯只读操作</li>
</ul>
<h3>常见误用:混淆 <code>std::is_sorted</code> 和 <code>std::is_sorted_until</code>
</h3>
<p><code>std::is_sorted</code> 只返回 <code>bool</code>;而 <code>std::is_sorted_until</code> 返回第一个破坏排序的迭代器(或 <code>end()</code>)。有人想定位哪出错了,却用了前者,结果只能知道“没排好”,不知道从哪开始坏的。</p>
<p>例如排查时更实用的是:</p>
<pre class="brush:php;toolbar:false;">auto bad = std::is_sorted_until(v.begin(), v.end());
if (bad != v.end()) {
std::cout <p>另外,别把 <code>std::is_sorted</code> 当作排序工具——它不排序,只检测。真要排序得用 <code>std::sort</code>。</p><p>最容易被忽略的一点:它对浮点数容器要格外小心。NaN 值会让 <code>operator 返回 false,导致 <code>std::is_sorted</code> 行为不可靠,这种场景建议先过滤或特殊处理 NaN。</code></p>C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










