C++:如何创建在运行时确定大小的成员二维数组

C++: How to create a member 2D-array of size determined at runtime

我试图声明一个指向指针的空指针,将其分配给在构造内存期间分配的指针,然后遍历它再次进行赋值,但我遗漏了一些东西。另外我想知道是否可以使用 std::array 来做到这一点。附上代码:

// Cell.h

class Cell {
    char contents;
    bool is_free;
};
// Memory.h

#include "Cell.h"
#include <cstddef>

class Memory {
public:
    Memory(std::size_t nlines, std::size_t ncols);
private:
    Cell **cells;
};
// Memory.cpp

#include "Memory.h"

Memory::Memory(std::size_t nlines, std::size_t ncols):
    cells(new Cell[nlines]) // Cannot initialize a member subobject of type 'Cell **' with an rvalue of type 'Cell *'
{
    for (std::size_t i = 0; i < nlines; ++i)
        cells[i] = new Cell[ncols];
}

此外,我需要我的数组在初始化后包含值为 char contents = '.', bool is_free = true 的单元格。哪种方法最好?

UPD:我考虑过使用单个指针(不是指向指针的指针)创建二维伪数组并使用 i*ncols + j.

访问单元格

Also I'm curious if it's possible to do this with the std::array

你不能,std::array 的大小被指定为模板参数并且你的数组是动态大小的。

与其处理原始指针,不如查看 std::vector 动态大小的数组:

std::vector<std::vector<Cell>> cells{ncols, std::vector{nlines, Cell{}}};

主要好处是您无需手动分配和管理内存。

UPD: I've thought of creating a 2D pseudo-array using a single pointer (not a pointer to a pointer) and accessing a cell with i*ncols + j.

这是一个更好的主意,将数据保存在单个平面向量中可以减少碎片。

std::vector<Cell> cells(nlines*ncols, Cell{});

为了使访问更容易,您可以将这个一维向量包装在一个 class 中,它公开一个 operator()(std::size_t row, std::size_t col),它执行从(行,列)索引到一维数组中位置的转换.

你需要写

Memory::Memory(std::size_t nlines, std::size_t ncols)
    :cells(new *Cell[nlines]) 
{
...
}

(注意 Cell * 而不是 Cell)。

std::array 只是编译时固定的数组大小,因此它不适合您的目的。

我同意您的修改。不要将指针数组用于矩阵,使用带有索引 i*ncols + j 的平面数组方法。这个前者更难使用并且开销更高(由于许多 new 调用)。

如果您担心乘法开销,您可以查找 table 以查找 i*ncols。但我怀疑它是否值得。