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

按长度排序字符串结果错误?C++ sort自定义谓词疑问

字符串向量排序逻辑问题解析

需求是对string类型的vector先按字符串长度升序排序,长度相同的再按字典序升序排序。

初始实现代码

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main() {

    vector<string> words {"zzz", "aaazzz", "zz", "a"};

    sort(words.begin(), words.end(), [](auto& w1, auto& w2) {
        if (w1.length() < w2.length()) {
            return true;
        }
        return w1 < w2;
    });

    for (auto& w : words) {
        cout << w << endl;
    }

    return 0;
}

错误运行结果

a
zz
aaazzz
zzz

修改后的排序逻辑代码

仅修改sort的lambda比较器:

sort(words.begin(), words.end(), [](auto& w1, auto& w2) {
    if (w1.length() == w2.length()) {
        return w1 < w2;
    }
    return w1.length() < w2.length();
});

正确运行结果

a
zz
zzz
aaazzz

问题原因分析

初始lambda的逻辑存在优先级错误:

  • 仅当w1.length() < w2.length()时返回true(这部分符合长度升序要求);
  • 但当w1长度大于w2时,代码直接返回w1 < w2的字典序比较结果。比如对比"aaazzz"(长度6)和"zzz"(长度3):此时w1.length() < w2.length()为false,代码返回"aaazzz" < "zzz"——这个字典序比较结果是true('a'的ASCII码小于'z'),导致sort将更长的"aaazzz"排在了更短的"zzz"前面,违背了「先按长度排序」的核心需求。

修改后的逻辑明确了优先级:

  1. 优先比较长度:长度不同时,直接按长度升序排列,完全不考虑字典序;
  2. 仅当长度相同时,才通过字典序比较调整顺序。

这样就严格遵循了「先长度、后字典序」的排序规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 04:08:17