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

C++11中对std::list使用sort函数的方法及代码修改咨询

问题分析与修正方案

核心问题

std::sort 需要随机访问迭代器才能正常工作,但 std::list 的迭代器属于双向迭代器,不满足 std::sort 的底层要求,所以直接调用 std::sort 对 std::list 完全无效。必须改用 std::list 自带的成员函数 sort()。

需要修改的两个部分

  • 替换排序调用:删掉 std::sort(std::begin(arr), std::end(arr), ...) 这一行,直接调用 arr.sort(...)。std::list::sort 不需要传递迭代器范围,直接在容器实例上调用即可。
  • 优化lambda参数(可选但推荐):把lambda里的 std::string l, std::string r 改成 const std::string& l, const std::string& r,避免不必要的字符串拷贝,提升运行性能。

修正后的完整代码

arr.sort(
    [](const std::string& l, const std::string& r){
        return l.substr(1) < r.substr(1);
    }
);

std::cout << "Sorted List: " << std::endl;
for (auto const & s: arr) {
    std::cout << s << std::endl;
}
std::cout << "The End" << std::endl;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:09:32