我如何声明一个2d数组使用新?
比如,对于一个“普通”数组,我将:
int* ary = new int[Size]
but
int** ary = new int[sizeY][sizeX]
A)不工作/编译b)没有完成什么:
int ary[sizeY][sizeX]
所做的事。
我如何声明一个2d数组使用新?
比如,对于一个“普通”数组,我将:
int* ary = new int[Size]
but
int** ary = new int[sizeY][sizeX]
A)不工作/编译b)没有完成什么:
int ary[sizeY][sizeX]
所做的事。
当前回答
如果你想要一个2d的整数数组,它的元素在内存中是按顺序分配的,你必须像这样声明它
int (*intPtr)[n] = new int[x][n]
你可以用任何维数来代替x,但是n在两个地方必须相等。例子
int (*intPtr)[8] = new int[75][8];
intPtr[5][5] = 6;
cout<<intPtr[0][45]<<endl;
必须打印6。
其他回答
Typedef是你的朋友
在回顾并查看了许多其他答案之后,我发现需要进行更深层次的解释,因为许多其他答案要么存在性能问题,要么迫使您使用不寻常的或繁重的语法来声明数组,或访问数组元素(或以上所有问题)。
首先,这个答案假设您在编译时知道数组的尺寸。如果你这样做,那么这是最好的解决方案,因为它将提供最好的性能,并允许您使用标准数组语法来访问数组元素。
The reason this gives the best performance is because it allocates all of the arrays as a contiguous block of memory meaning that you are likely to have less page misses and better spacial locality. Allocating in a loop may cause the individual arrays to end up scattered on multiple non-contiguous pages through the virtual memory space as the allocation loop could be interrupted ( possibly multiple times ) by other threads or processes, or simply due to the discretion of the allocator filling in small, empty memory blocks it happens to have available.
其他好处是声明语法简单,数组访问语法标准。
在c++中使用new:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
typedef double (array5k_t)[5000];
array5k_t *array5k = new array5k_t[5000];
array5k[4999][4999] = 10;
printf("array5k[4999][4999] == %f\n", array5k[4999][4999]);
return 0;
}
或使用calloc的C样式:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
typedef double (*array5k_t)[5000];
array5k_t array5k = calloc(5000, sizeof(double)*5000);
array5k[4999][4999] = 10;
printf("array5k[4999][4999] == %f\n", array5k[4999][4999]);
return 0;
}
在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是很简单的。
int** ary = new int[sizeY][sizeX]
应该是:
int **ary = new int*[sizeY];
for(int i = 0; i < sizeY; ++i) {
ary[i] = new int[sizeX];
}
然后清理是:
for(int i = 0; i < sizeY; ++i) {
delete [] ary[i];
}
delete [] ary;
编辑:正如Dietrich Epp在评论中指出的那样,这并不是一个轻量级的解决方案。另一种方法是使用一个大内存块:
int *ary = new int[sizeX*sizeY];
// ary[i][j] is then rewritten as
ary[i*sizeY+j]
下面的例子可能会有所帮助,
int main(void)
{
double **a2d = new double*[5];
/* initializing Number of rows, in this case 5 rows) */
for (int i = 0; i < 5; i++)
{
a2d[i] = new double[3]; /* initializing Number of columns, in this case 3 columns */
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
a2d[i][j] = 1; /* Assigning value 1 to all elements */
}
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
cout << a2d[i][j] << endl; /* Printing all elements to verify all elements have been correctly assigned or not */
}
}
for (int i = 0; i < 5; i++)
delete[] a2d[i];
delete[] a2d;
return 0;
}
我在创建动态数组时使用这个。如果你有一个类或结构。这是可行的。例子:
struct Sprite {
int x;
};
int main () {
int num = 50;
Sprite **spritearray;//a pointer to a pointer to an object from the Sprite class
spritearray = new Sprite *[num];
for (int n = 0; n < num; n++) {
spritearray[n] = new Sprite;
spritearray->x = n * 3;
}
//delete from random position
for (int n = 0; n < num; n++) {
if (spritearray[n]->x < 0) {
delete spritearray[n];
spritearray[n] = NULL;
}
}
//delete the array
for (int n = 0; n < num; n++) {
if (spritearray[n] != NULL){
delete spritearray[n];
spritearray[n] = NULL;
}
}
delete []spritearray;
spritearray = NULL;
return 0;
}