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

如何访问并打印C++动态list<int>数组中的元素?

问题分析与解决

首先你的代码存在核心错误:new list<int>(4) 创建的是一个包含4个默认值(0)的list<int>对象,而非你预期的「包含4个list<int>的动态数组」。这直接导致后续访问a[2]属于越界访问(未定义行为),范围for循环的异常也源于此。

正确创建动态list数组

要创建包含N个list<int>的动态数组,需用方括号指定数组大小:

#include <iostream>
#include <list>
using namespace std;

int main() {
    // 创建包含4个空list<int>的动态数组
    list<int>* a = new list<int>[4];
    
    a[0].push_back(1);
    a[0].push_back(3);
    a[2].push_back(5);
    a[2].push_back(7);
    
    // 现在可正常访问各个list
    cout << a[0].front() << '\n'; // 输出1
    cout << a[2].back() << '\n';  // 输出7

打印单个list的元素

方式1:范围for循环(C++11及以上支持)

此时a[0]是合法的list<int>对象,范围for循环可正常工作:

// 打印a[0]中的所有元素
for (auto element : a[0]) {
    cout << element << '\n';
}
// 输出:1、3

方式2:迭代器遍历

兼容更早C++标准或需要精细控制时,可使用迭代器:

// 打印a[2]中的所有元素
for (list<int>::iterator it = a[2].begin(); it != a[2].end(); ++it) {
    cout << *it << '\n';
}
// 输出:5、7

方式3:通过front()和pop_front()(不推荐,会修改原list)

适合一次性打印且无需保留原数据的场景,需注意会弹出元素:

list<int> temp = a[0]; // 复制一份避免修改原list
while (!temp.empty()) {
    cout << temp.front() << '\n';
    temp.pop_front();
}

注意事项

  • 使用动态数组后,必须用delete[] a;释放内存,避免泄漏:
delete[] a;
    return 0;
}
  • 更推荐用vector<list<int>>替代手动管理的动态数组,它会自动处理内存,更安全便捷:
vector<list<int>> a(4);
// 用法和动态数组完全一致,无需手动delete

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 08:40:27