用 std::sort 配合 lambda 比较器可按长度排序字符串,关键在于自定义比较逻辑而非修改数据结构,常见错误是冗余判断;std::string_view 更高效但需保证生命周期;s.length() 不会返回负数,误转 int 可能引发问题。

用 std::sort 配合 lambda 比较器是最直接的方法
标准库的 std::sort 默认按字典序排 std::string,但只要传入自定义比较逻辑,就能按长度排序。关键不是改数据结构,而是告诉 sort “怎么比”。
常见错误是写成 a.length() 却忘了加 <code>const & 引用,导致不必要的拷贝;或者把比较器写成返回 void 或用 = 赋值,编译直接报错。
- 必须用
const std::string&接收参数,避免复制开销 - 比较器要返回
bool,且满足严格弱序(不能写成) - 数组可以是
std::vector<:string></:string>、std::array或原始 C 风格数组(需传指针范围)
std::vector<:string> arr = {"hi", "hello", "a", "world"};
std::sort(arr.begin(), arr.end(), [](const std::string& a, const std::string& b) {
return a.length() <h3>原始 C 风格<a style="color:#f60; text-decoration:underline;" title="字符串数组" href="https://m.php.cn/zt/52359.html" target="_blank">字符串数组</a>需要额外处理</h3>
<p>如果用的是 <code>char*</code> 数组(比如 <code>const char* arr[]</code>),<code>std::sort</code> 不能直接调用 <code>strlen</code>——因为比较器里对空指针或未初始化指针调用 <code>strlen</code> 会崩溃。</p>
<p>使用场景多见于 legacy 代码或嵌入式环境,此时必须确保所有指针有效,且最好用 <code>std::strlen</code>(来自 <code><cstring></cstring></code>)而非 <code>std::string::length()</code>。</p>
<ul>
<li>原始数组需用 <code>std::begin</code>/<code>std::end</code> 或手动传指针边界</li>
<li>比较器中先判空再算长度,否则 <code>strlen(nullptr)</code> 是未定义行为</li>
<li>若字符串可能含嵌入空字符(如二进制数据),<code>strlen</code> 不适用,得换其他长度来源</li>
</ul>
<pre class="brush:php;toolbar:false;">const char* arr[] = {"cat", "dog", "elephant", "ant"};
std::sort(std::begin(arr), std::end(arr), [](const char* a, const char* b) {
return (a ? std::strlen(a) : 0) <h3>降序排列和稳定性要注意什么</h3><p>升序是 <code>a.length() ,降序只需改成 <code>a.length() > b.length()</code>。但注意:<code>std::sort</code> 是不稳定排序,相同长度的字符串相对顺序可能改变。</code></p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill4025" title="C++ 算法竞赛自动化测试数据生成与校验框架"><img
src="https://img.php.cn/upload/skill/000/000/081/178988956499722.jpg" alt="C++ 算法竞赛自动化测试数据生成与校验框架" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill4025" title="C++ 算法竞赛自动化测试数据生成与校验框架" class="overflowclass">C++ 算法竞赛自动化测试数据生成与校验框架</a>
<p class="overflowclass">根据原题生成新题面、验证器及完整测试数据,自动套用 testlib 模板,用于用户要求生成测试数据时。</p>
</div>
<a rel="nofollow" href="/xiazai/skill4025" title="C++ 算法竞赛自动化测试数据生成与校验框架" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p>如果要求“长度相同时保持原有顺序”,就得用 <code>std::stable_sort</code>,性能略低(O(n log²n) vs O(n log n)),但语义明确。</p>
- 降序写法别漏掉括号,比如
!a.empty() && a.length() > b.length()容易误写成!a.empty() && a.length() > b.length() && !b.empty()这种冗余判断 -
std::stable_sort在小数组上差异不明显,但大数据量时缓存友好性稍差 - 若用
std::string_view替代std::string,长度获取更快(无动态分配干扰),但前提是字符串生命周期足够长
遇到 std::string::length() 返回负数?那是误用了 size() 的有符号版本
极少见但容易困惑:如果代码里写了 static_cast<int>(s.length()) 并触发了警告或异常,说明你误以为 <code>length() 可能为负——其实它返回 size_t(无符号),永远 ≥ 0。任何与负数比较都会引发隐式转换问题。
典型症状是编译警告 “comparison of integer expressions of different signedness”,或运行时逻辑错乱(比如 4294967295 成立)。
- 永远不要把
length()或size()转成int再比较,除非你明确知道长度不会超INT_MAX - 比较两个长度时,类型自动匹配;若需参与有符号运算,用
static_cast<long long>(s.length())</long>更安全 - Clang/GCC 加
-Wsign-compare能提前捕获这类隐患
C++ 字符串长度排序本身不难,真正容易出问题的是边界指针、有符号/无符号混用、以及忽略稳定性的业务需求。动手前先确认数据来源是否可信,比写对 lambda 更重要。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










