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

C++中max_element处理string向量时返回结果不符合预期问题

问题根源

std::max_element 默认通过元素类型的 < 运算符完成比较,std::string 的 < 运算符实现的是字典序比较,和字符串长度无关。
测试用例中返回"yely",是因为该字符串首字母y的字典序比其余几个字符串的首字母都靠后,是数组内字典序最大的元素,完全符合max_element默认规则的返回逻辑,和「查找长度最长字符串」的需求不匹配。

修正方案

调用max_element时传入自定义比较器,指定比较规则为字符串长度,即可正确获取长度最长的元素。修正后代码如下:

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

vector<string> solution(vector<string> inputArray) {
    vector<string> res;
    // 按字符串长度比较找最大值
    auto longest = *max_element(inputArray.begin(), inputArray.end(),
        [](const std::string& a, const std::string& b) {
            return a.length() < b.length();
        });
    size_t maxLen = longest.length();
    for (const auto& str : inputArray) {
        if (str.length() == maxLen) {
            res.push_back(str);
        }
    }
    return res;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.05 16:18:27