我如何声明一个2d数组使用新?

比如,对于一个“普通”数组,我将:

int* ary = new int[Size]

but

int** ary = new int[sizeY][sizeX]

A)不工作/编译b)没有完成什么:

int ary[sizeY][sizeX] 

所做的事。


当前回答

在c++ 11及以上版本中,我推荐两种通用技术,一种用于编译时维度,另一种用于运行时维度。这两个答案都假设您需要统一的二维数组(而不是锯齿状数组)。

编译时维度

使用std::array的std::array,然后使用new把它放到堆上:

// the alias helps cut down on the noise:
using grid = std::array<std::array<int, sizeX>, sizeY>;
grid * ary = new grid;

同样,这仅适用于在编译时已知维度大小的情况。

运行时维度

实现只有在运行时才知道大小的二维数组的最佳方法是将其包装到一个类中。该类将分配一个1d数组,然后重载操作符[]来为第一个维度提供索引。 这是因为在c++中,2D数组是行为主的:

(摘自http://eli.thegreenplace.net/2015/memory-layout-of-multi-dimensional-arrays/)

连续的内存序列有利于提高性能,而且易于清理。下面是一个示例类,省略了很多有用的方法,但显示了基本思想:

#include <memory>

class Grid {
  size_t _rows;
  size_t _columns;
  std::unique_ptr<int[]> data;

public:
  Grid(size_t rows, size_t columns)
      : _rows{rows},
        _columns{columns},
        data{std::make_unique<int[]>(rows * columns)} {}

  size_t rows() const { return _rows; }

  size_t columns() const { return _columns; }

  int *operator[](size_t row) { return row * _columns + data.get(); }

  int &operator()(size_t row, size_t column) {
    return data[row * _columns + column];
  }
}

因此,我们用std::make_unique<int[]>(行*列)项创建一个数组。我们重载操作符[],它将为我们索引行。它返回一个int *,指向该行的开头,然后可以像对列一样对该行进行解引用。注意,make_unique在c++ 14中首次发布,但如果需要,可以在c++ 11中填充它。

对于这些类型的结构,重载operator()也是很常见的:

  int &operator()(size_t row, size_t column) {
    return data[row * _columns + column];
  }

从技术上讲,我在这里没有使用new,但是从std::unique_ptr<int[]>移动到int *并使用new/delete是很简单的。

其他回答

如果行长是编译时常数,c++ 11允许

auto arr2d = new int [nrows][CONSTANT];

请看这个答案。像gcc这样的编译器允许将变长数组作为c++的扩展,可以使用如下所示的new来获得完全的运行时可变数组维度功能,就像C99所允许的那样,但是可移植的ISO c++仅限于第一个维度是变量。

另一个有效的选择是手动对一个大的1d数组进行2d索引,正如另一个答案所示,允许与真正的2d数组相同的编译器优化(例如,证明或检查数组不会彼此别名/重叠)。


否则,您可以使用指向数组的指针数组来支持类似连续2D数组的2D语法,尽管这不是一个有效的单一大分配。你可以使用循环初始化它,就像这样:

int** a = new int*[rowCount];
for(int i = 0; i < rowCount; ++i)
    a[i] = new int[colCount];

上面,对于colCount= 5和rowCount = 4,将产生以下结果:

在删除指针数组之前,不要忘记使用循环单独删除每一行。另一个答案中的例子。

这个问题一直困扰着我——这是一个很常见的问题,应该已经有了一个好的解决方案,比向量的向量或滚动你自己的数组索引更好的解决方案。

当c++中应该存在一些东西,但却不存在时,第一个地方是boost.org。在那里我找到了Boost多维数组库,multi_array。它甚至包括一个multi_array_ref类,可用于包装您自己的一维数组缓冲区。

尽管这个流行的答案将为您提供所需的索引语法,但它的效率是双重的:在空间和时间上都大而慢。有更好的办法。

为什么答案又大又慢

建议的解决方案是创建一个指针的动态数组,然后将每个指针初始化到它自己的独立动态数组。这种方法的优点是它提供了你习惯的索引语法,所以如果你想找到矩阵在x,y位置的值,你说:

int val = matrix[ x ][ y ];

这是因为矩阵[x]返回一个指向数组的指针,然后用[y]作为索引。分解一下:

int* row = matrix[ x ];
int  val = row[ y ];

方便,是吗?我们喜欢[x][y]语法。

但是这个解决方案有一个很大的缺点,那就是它既胖又慢。

Why?

The reason that it's both fat and slow is actually the same. Each "row" in the matrix is a separately allocated dynamic array. Making a heap allocation is expensive both in time and space. The allocator takes time to make the allocation, sometimes running O(n) algorithms to do it. And the allocator "pads" each of your row arrays with extra bytes for bookkeeping and alignment. That extra space costs...well...extra space. The deallocator will also take extra time when you go to deallocate the matrix, painstakingly free-ing up each individual row allocation. Gets me in a sweat just thinking about it.

它慢还有另一个原因。这些单独的分配往往位于内存的不连续部分。一行的地址可能是1000,另一行的地址可能是100000——你可以理解。这意味着当你在穿越矩阵时,你就像一个狂野的人一样在记忆中跳跃。这往往会导致缓存丢失,从而大大降低处理时间。

所以,如果你绝对必须有你可爱的[x][y]索引语法,使用这个解决方案。如果你想要快速和小巧(如果你不关心这些,为什么要用c++ ?),你需要一个不同的解决方案。

不同的解决方案

更好的解决方案是将整个矩阵分配为单个动态数组,然后使用自己的(稍微)聪明的索引数学来访问单元格。索引的数学运算非常巧妙;不,这一点也不聪明:这是显而易见的。

class Matrix
{
    ...
    size_t index( int x, int y ) const { return x + m_width * y; }
};

给定这个index()函数(我想象它是一个类的成员,因为它需要知道矩阵的m_width),您可以访问矩阵数组中的单元格。矩阵数组是这样分配的:

array = new int[ width * height ];

所以在缓慢的,高脂肪的溶液中

array[ x ][ y ]

...这是一个快速,小的解决方案:

array[ index( x, y )]

很难过,我知道。但你会习惯的。你的CPU会感谢你的。

我不确定是否没有提供以下答案 但我决定在2d数组的分配中添加一些局部优化 (例如,一个方阵只通过一次分配完成): Int ** mat = new Int *[n]; Mat [0] = new int [n * n];

然而,由于上述分配的线性,删除是这样的: 删除[]mat[0]; 删除[]mat;

这里,我有两个选择。第一个展示了数组的数组或指针的指针的概念。我更喜欢第二个,因为地址是连续的,正如您在图像中看到的那样。

#include <iostream>

using namespace std;


int main(){

    int **arr_01,**arr_02,i,j,rows=4,cols=5;

    //Implementation 1
    arr_01=new int*[rows];

    for(int i=0;i<rows;i++)
        arr_01[i]=new int[cols];

    for(i=0;i<rows;i++){
        for(j=0;j<cols;j++)
            cout << arr_01[i]+j << " " ;
        cout << endl;
    }


    for(int i=0;i<rows;i++)
        delete[] arr_01[i];
    delete[] arr_01;


    cout << endl;
    //Implementation 2
    arr_02=new int*[rows];
    arr_02[0]=new int[rows*cols];
    for(int i=1;i<rows;i++)
        arr_02[i]=arr_02[0]+cols*i;

    for(int i=0;i<rows;i++){
        for(int j=0;j<cols;j++)
            cout << arr_02[i]+j << " " ;
        cout << endl;
    }

    delete[] arr_02[0];
    delete[] arr_02;


    return 0;
}