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

为什么这段获取最长字符串的C++函数返回空vector?

问题修复方案

你的代码存在两个核心问题,导致返回的vector为空:

1. 未初始化的局部变量

highestSize和add都是未初始化的局部变量,会包含随机垃圾值:

  • highestSize初始值不确定,第一次调用max时无法正确计算最长字符串长度,甚至会引发异常行为
  • add的随机值作为newArray的索引时,会触发越界访问,属于未定义行为

2. 错误的vector元素添加方式

newArray初始为空,直接用newArray[add] = inputArray[i]会访问不存在的元素位置,正确的做法是使用push_back方法向vector末尾追加元素,无需手动维护索引变量。

修复后的代码

vector<string> solution(vector<string> inputArray) {
    int highestSize = 0; // 初始化最大长度为0
    vector<string> newArray{};

    // 遍历获取最长字符串的长度
    for (const string& s : inputArray) {
        highestSize = max(static_cast<int>(s.length()), highestSize);
    }

    // 收集所有符合长度要求的字符串
    for (const string& s : inputArray) {
        if (s.length() == highestSize) {
            newArray.push_back(s);
        }
    }

    return newArray;
}

额外优化说明

  • 使用范围for循环替代传统下标循环,代码更简洁易读
  • 用static_cast<int>替代C风格强制转换,符合C++语法规范
  • 遍历字符串时使用const string&避免不必要的拷贝,提升运行效率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 12:24:21