【问题标题】:accessing elements of dynamic array of lists访问列表的动态数组的元素
【发布时间】:2022-11-13 19:17:19
【问题描述】:

所以,我不知道如何打印这样一个列表的元素。 `

list<int>* a;
    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);

    cout << a[0].front() << '\n';
    cout << a[1].back() << '\n';

`

首先,我尝试通过基于范围的 for 循环打印它,但它也不起作用。

for(auto element: a[0]) cout << element << '\n';    // doesn't work

【问题讨论】:

  • a = 新列表<int>[4];
  • a 是指向包含四个元素的列表,它们都为零;只有a[0](又名*a)有效。使用任何其他索引具有未定义的行为。
  • 请比“不起作用”更具体。

标签: c++ stdlist


【解决方案1】:

我会使用std::vector 而不是new(在这种情况下,技术上应该是new[])。

#include <iostream>
#include <list>
#include <vector>

int main() {
    std::vector<std::list<int>> a(4);
    a[0].push_back(1);
    a[0].push_back(3);
    a[2].push_back(5);
    a[2].push_back(7);

    for (std::list<int> const& l : a) {
        for (int i : l) { 
            std::cout << i << ' ';
        }
        std::cout << '
';
    }
}

输出

1 3

5 7
 

【讨论】:

    【解决方案2】:

    您是否要存储整数列表列表?因为这个实现将不起作用,因为您只有一个整数列表,并且没有可用于元素的 push_back() 操作。

    删除所有这些 push_back() 操作的索引运算符,并取出 front() 和 back() 的索引运算符,因为这些元素也不可用。

    【讨论】:

      猜你喜欢
      • 2016-12-13
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多