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

C++中如何按字符串长度排序字符串数组?竞赛向实现及错误排查

字符串数组按长度排序的正确实现(竞赛编程版)

问题根源

你代码里的sort(s->begin(), s->end())完全用错了——s->begin()是取数组第一个字符串的字符起始迭代器,s->end()是这个字符串的字符结束迭代器,所以这段代码其实是把第一个字符串"midnight"的字符按字典序排序,变成了dghiimnt,这就是首个输出异常的原因。你需要的是对整个字符串数组排序,而不是单个字符串内部的字符。

竞赛级简洁实现方案

竞赛里常用两种写法,都能高效解决问题:

方式1:C++11+ Lambda表达式(推荐,代码紧凑)

直接在sort里传入匿名比较规则,按字符串长度降序排列:

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main()
{
    string s[] = {"midnight", "Coder", "comp", "Wedn", "Top", "at"};
    int n = sizeof(s)/sizeof(s[0]);
    // 按长度降序,长度相同可追加字典序规则(比如return a.size() > b.size() || (a.size() == b.size() && a < b);)
    sort(s, s + n, [](const string& a, const string& b) {
        return a.size() > b.size();
    });
    // 范围for循环更简洁,竞赛里常用
    for (const auto& str : s) cout << str << " ";
    return 0;
}

方式2:自定义比较函数(兼容旧C++标准)

如果竞赛环境不支持C++11,就单独写个比较函数:

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

bool cmp(const string& a, const string& b) {
    return a.size() > b.size(); // 长度降序
}

int main()
{
    string s[] = {"midnight", "Coder", "comp", "Wedn", "Top", "at"};
    int n = sizeof(s)/sizeof(s[0]);
    sort(s, s + n, cmp);
    for (int i = 0; i < n; i++) cout << s[i] << " ";
    return 0;
}

输出结果

运行后会得到你期望的:midnight Coder comp Wedn Top at

核心要点

  • sort的正确范围是数组起始地址s到s + n(覆盖整个数组),不是单个字符串的迭代器。
  • 若要升序排列,把比较规则里的>改成<即可。
  • 竞赛里优先用Lambda,少写额外函数,代码更简洁高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:36:29