如何用C++声明二维数组?

How do I declare a 2d array in C++ using new?

如何使用new声明二维数组?

比如,对于"普通"数组,我会:

1
int* ary = new int[Size]

但是

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

a)不能工作/编译,b)不能完成以下任务:

1
int ary[sizeY][sizeX]

做。


动态二维数组基本上是指向数组的指针数组。您可以使用循环初始化它,如下所示:

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

对于colCount= 5rowCount = 4,上述内容将产生以下内容:

enter image description here


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

应该是:

1
2
3
4
int **ary = new int*[sizeY];
for(int i = 0; i < sizeY; ++i) {
    ary[i] = new int[sizeX];
}

然后清理将是:

1
2
3
4
for(int i = 0; i < sizeY; ++i) {
    delete [] ary[i];
}
delete [] ary;

编辑:正如DietrichEPP在评论中指出的,这并不是一个轻量级的解决方案。另一种方法是使用一个大内存块:

1
2
3
4
int *ary = new int[sizeX*sizeY];

// ary[i][j] is then rewritten as
ary[i*sizeY+j]


虽然这个流行的答案会给你想要的索引语法,但是它的效率是双重的:在空间和时间上都是大的和慢的。有更好的方法。

为什么这个答案又大又慢

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

1
int val = matrix[ x ][ y ];

这是因为矩阵[X]返回指向数组的指针,然后用[Y]索引该数组。分解:

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

方便,是吗?我们喜欢我们的[X][Y]语法。

但解决方案有一个很大的缺点,即既胖又慢。

为什么?

它既胖又慢的原因实际上是一样的。矩阵中的每个"行"都是一个单独分配的动态数组。进行堆分配在时间和空间上都很昂贵。分配器需要时间进行分配,有时运行O(N)算法进行分配。分配程序用额外的字节"填充"每个行数组,以便记账和对齐。额外的空间需要……嗯……额外的空间。DealLocator还需要额外的时间来解除矩阵的分配,这会使每一行的分配都得到极大的解放。一想到这件事我就大汗淋漓。

另一个原因是速度慢。这些独立的分配往往存在于不连续的内存部分中。一行可能在地址1000,另一行在地址100000,你明白了。这意味着当你穿越矩阵的时候,你就像一个狂野的人在记忆中跳跃。这往往会导致缓存未命中,从而大大降低处理时间。

因此,如果您绝对必须有可爱的[X][Y]索引语法,请使用该解决方案。如果你想要快速和小(如果你不关心那些,为什么你在C++中工作?),您需要一个不同的解决方案。

另一种解决方案

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

1
2
3
4
5
class Matrix
{
    ...
    size_t index( int x, int y ) const { return x + m_width * y; }
};

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

1
array = new int[ width * height ];

因此,在缓慢的脂肪溶液中,这相当于:

1
array[ x ][ y ]

…这是快速、小的解决方案吗:

1
array[ index( x, y )]

悲伤,我知道。但你会习惯的。你的CPU会感谢你的。


在C++ 11中是可能的:

1
auto array = new double[M][N];

这样,内存就不会初始化。要初始化它,请执行以下操作:

1
auto array = new double[M][N]();

示例程序(用G++STD= C++ 11编译):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <utility>
#include <type_traits>
#include <typeinfo>
#include <cxxabi.h>
using namespace std;

int main()
{
    const auto M = 2;
    const auto N = 2;

    // allocate (no initializatoin)
    auto array = new double[M][N];

    // pollute the memory
    array[0][0] = 2;
    array[1][0] = 3;
    array[0][1] = 4;
    array[1][1] = 5;

    // re-allocate, probably will fetch the same memory block (not portable)
    delete[] array;
    array = new double[M][N];

    // show that memory is not initialized
    for(int r = 0; r < M; r++)
    {
        for(int c = 0; c < N; c++)
            cout << array[r][c] <<"";
        cout << endl;
    }
    cout << endl;

    delete[] array;

    // the proper way to zero-initialize the array
    array = new double[M][N]();

    // show the memory is initialized
    for(int r = 0; r < M; r++)
    {
        for(int c = 0; c < N; c++)
            cout << array[r][c] <<"";
        cout << endl;
    }

    int info;
    cout << abi::__cxa_demangle(typeid(array).name(),0,0,&info) << endl;

    return 0;
}

输出:

1
2
3
4
5
6
2 4
3 5

0 0
0 0
double (*) [2]


从静态数组的例子中,我假定您需要一个矩形数组,而不是锯齿形数组。您可以使用以下内容:

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

然后可以访问以下元素:

1
ary[y*sizeX + x]

别忘了在ary上使用delete[]。


在C++ 11和以上,我推荐两种通用的技术,一种是编译时维度,一种是运行时技术。这两个答案都假定您需要统一的二维数组(而不是锯齿数组)。

编译时维度

使用std::arraystd::array,然后使用new将其放到堆中:

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

同样,只有在编译时知道维度的大小时,这才有效。

运行时维度

实现只有在运行时才知道大小的二维数组的最佳方法是将其包装成一个类。类将分配一个一维数组,然后重载operator []以为第一个维度提供索引。这是因为在C++中,一个2D数组是行的主要部分:

 matrix shown in logical form and one-dimensional form

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

由于性能原因,连续的内存序列是很好的,而且也很容易清理。下面是一个示例类,它省略了许多有用的方法,但显示了基本思想:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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(rows * columns)个条目的数组。我们超载了operator [],它将为我们索引行。它返回一个指向行的开始的int *,然后可以取消对该列的正常引用。注意,EDCOX1 7是第一个在C++ 14中的船,但如果需要的话,可以在C++ 11中填充它。

这些类型的结构也常见于超载operator()

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

从技术上讲,我在这里没有使用过new,但是从std::unique_ptrint *并使用new/delete是很简单的。


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

当某些东西应该存在于C++中,但不存在时,首先要查找的是Boo..Org。在那里我找到了Boost多维数组库,multi_array。它甚至包括一个multi_array_ref类,可以用来包装自己的一维数组缓冲区。


为什么不使用stl:vector?很简单,你不需要删除向量。

1
2
3
4
int rows = 100;
int cols = 200;
vector< vector<int> > f(rows, vector<int>(cols));
f[rows - 1][cols - 1] = 0; // use it like arrays

资料来源:如何在C/C++中创建2, 3(或多)维数组?


如何在GNU C++中分配连续多维数组?有一个GNU扩展允许"标准"语法工作。

问题似乎来自于新的操作员。请确保使用operator new:

1
double (* in)[n][n] = new (double[m][n][n]);  // GNU extension

仅此而已:你得到了一个与C兼容的多维数组…


二维数组基本上是一个一维指针数组,其中每个指针都指向一个一维数组,该数组将保存实际数据。

这里n是行,m是列。

动态分配

1
2
3
int** ary = new int*[N];
  for(int i = 0; i < N; i++)
      ary[i] = new int[M];

填满

1
2
3
for(int i = 0; i < N; i++)
    for(int j = 0; j < M; j++)
      ary[i][j] = i;

打印

1
2
3
4
for(int i = 0; i < N; i++)
    for(int j = 0; j < M; j++)
      std::cout << ary[i][j] <<"
"
;

自由的

1
2
3
for(int i = 0; i < N; i++)
    delete [] ary[i];
delete [] ary;

typedef是你的朋友

在回顾并查看了许多其他答案之后,我发现有一个更深入的解释是正确的,因为许多其他答案要么有性能问题,要么强迫您使用异常或繁琐的语法来声明数组,要么访问数组元素(或以上所有元素)。

首先,这个答案假设您在编译时知道数组的维数。如果这样做,那么这是最好的解决方案,因为它既能提供最佳性能,又允许您使用标准数组语法来访问数组元素。

之所以能获得最佳性能,是因为它将所有数组分配为一个连续的内存块,这意味着您可能会有更少的页面遗漏和更好的空间位置。在一个循环中分配可能会导致单个数组通过虚拟内存空间分散在多个非连续页上,因为分配循环可能会被其他线程或进程中断(可能多次),或者仅仅是由于分配程序填充了小的、空的内存块,它恰好有一个可撤销的。

其他好处是简单的声明语法和标准数组访问语法。

在C++中使用新的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#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
"
, array5k[4999][4999]);

return 0;
}

或使用calloc的c样式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#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
"
, array5k[4999][4999]);

return 0;
}


这个问题困扰了我15年,所提供的解决方案对我来说都不满意。如何在内存中连续创建动态多维数组?今天我终于找到了答案。使用以下代码,您可以这样做:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>

int main(int argc, char** argv)
{
    if (argc != 3)
    {
        std::cerr <<"You have to specify the two array dimensions" << std::endl;
        return -1;
    }

    int sizeX, sizeY;

    sizeX = std::stoi(argv[1]);
    sizeY = std::stoi(argv[2]);

    if (sizeX <= 0)
    {
        std::cerr <<"Invalid dimension x" << std::endl;
        return -1;
    }
    if (sizeY <= 0)
    {
        std::cerr <<"Invalid dimension y" << std::endl;
        return -1;
    }

    /******** Create a two dimensional dynamic array in continuous memory ******
     *
     * - Define the pointer holding the array
     * - Allocate memory for the array (linear)
     * - Allocate memory for the pointers inside the array
     * - Assign the pointers inside the array the corresponding addresses
     *   in the linear array
     **************************************************************************/


    // The resulting array
    unsigned int** array2d;

    // Linear memory allocation
    unsigned int* temp = new unsigned int[sizeX * sizeY];

    // These are the important steps:
    // Allocate the pointers inside the array,
    // which will be used to index the linear memory
    array2d = new unsigned int*[sizeY];

    // Let the pointers inside the array point to the correct memory addresses
    for (int i = 0; i < sizeY; ++i)
    {
        array2d[i] = (temp + i * sizeX);
    }



    // Fill the array with ascending numbers
    for (int y = 0; y < sizeY; ++y)
    {
        for (int x = 0; x < sizeX; ++x)
        {
            array2d[y][x] = x + y * sizeX;
        }
    }



    // Code for testing
    // Print the addresses
    for (int y = 0; y < sizeY; ++y)
    {
        for (int x = 0; x < sizeX; ++x)
        {
            std::cout << std::hex << &(array2d[y][x]) << ' ';
        }
    }
    std::cout <<"

"
;

    // Print the array
    for (int y = 0; y < sizeY; ++y)
    {
        std::cout << std::hex << &(array2d[y][0]) << std::dec;
        std::cout <<":";
        for (int x = 0; x < sizeX; ++x)
        {
            std::cout << array2d[y][x] << ' ';
        }
        std::cout << std::endl;
    }



    // Free memory
    delete[] array2d[0];
    delete[] array2d;
    array2d = nullptr;

    return 0;
}

当使用sizex=20和sizey=15值调用程序时,输出如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
0x603010 0x603014 0x603018 0x60301c 0x603020 0x603024 0x603028 0x60302c 0x603030 0x603034 0x603038 0x60303c 0x603040 0x603044 0x603048 0x60304c 0x603050 0x603054 0x603058 0x60305c 0x603060 0x603064 0x603068 0x60306c 0x603070 0x603074 0x603078 0x60307c 0x603080 0x603084 0x603088 0x60308c 0x603090 0x603094 0x603098 0x60309c 0x6030a0 0x6030a4 0x6030a8 0x6030ac 0x6030b0 0x6030b4 0x6030b8 0x6030bc 0x6030c0 0x6030c4 0x6030c8 0x6030cc 0x6030d0 0x6030d4 0x6030d8 0x6030dc 0x6030e0 0x6030e4 0x6030e8 0x6030ec 0x6030f0 0x6030f4 0x6030f8 0x6030fc 0x603100 0x603104 0x603108 0x60310c 0x603110 0x603114 0x603118 0x60311c 0x603120 0x603124 0x603128 0x60312c 0x603130 0x603134 0x603138 0x60313c 0x603140 0x603144 0x603148 0x60314c 0x603150 0x603154 0x603158 0x60315c 0x603160 0x603164 0x603168 0x60316c 0x603170 0x603174 0x603178 0x60317c 0x603180 0x603184 0x603188 0x60318c 0x603190 0x603194 0x603198 0x60319c 0x6031a0 0x6031a4 0x6031a8 0x6031ac 0x6031b0 0x6031b4 0x6031b8 0x6031bc 0x6031c0 0x6031c4 0x6031c8 0x6031cc 0x6031d0 0x6031d4 0x6031d8 0x6031dc 0x6031e0 0x6031e4 0x6031e8 0x6031ec 0x6031f0 0x6031f4 0x6031f8 0x6031fc 0x603200 0x603204 0x603208 0x60320c 0x603210 0x603214 0x603218 0x60321c 0x603220 0x603224 0x603228 0x60322c 0x603230 0x603234 0x603238 0x60323c 0x603240 0x603244 0x603248 0x60324c 0x603250 0x603254 0x603258 0x60325c 0x603260 0x603264 0x603268 0x60326c 0x603270 0x603274 0x603278 0x60327c 0x603280 0x603284 0x603288 0x60328c 0x603290 0x603294 0x603298 0x60329c 0x6032a0 0x6032a4 0x6032a8 0x6032ac 0x6032b0 0x6032b4 0x6032b8 0x6032bc 0x6032c0 0x6032c4 0x6032c8 0x6032cc 0x6032d0 0x6032d4 0x6032d8 0x6032dc 0x6032e0 0x6032e4 0x6032e8 0x6032ec 0x6032f0 0x6032f4 0x6032f8 0x6032fc 0x603300 0x603304 0x603308 0x60330c 0x603310 0x603314 0x603318 0x60331c 0x603320 0x603324 0x603328 0x60332c 0x603330 0x603334 0x603338 0x60333c 0x603340 0x603344 0x603348 0x60334c 0x603350 0x603354 0x603358 0x60335c 0x603360 0x603364 0x603368 0x60336c 0x603370 0x603374 0x603378 0x60337c 0x603380 0x603384 0x603388 0x60338c 0x603390 0x603394 0x603398 0x60339c 0x6033a0 0x6033a4 0x6033a8 0x6033ac 0x6033b0 0x6033b4 0x6033b8 0x6033bc 0x6033c0 0x6033c4 0x6033c8 0x6033cc 0x6033d0 0x6033d4 0x6033d8 0x6033dc 0x6033e0 0x6033e4 0x6033e8 0x6033ec 0x6033f0 0x6033f4 0x6033f8 0x6033fc 0x603400 0x603404 0x603408 0x60340c 0x603410 0x603414 0x603418 0x60341c 0x603420 0x603424 0x603428 0x60342c 0x603430 0x603434 0x603438 0x60343c 0x603440 0x603444 0x603448 0x60344c 0x603450 0x603454 0x603458 0x60345c 0x603460 0x603464 0x603468 0x60346c 0x603470 0x603474 0x603478 0x60347c 0x603480 0x603484 0x603488 0x60348c 0x603490 0x603494 0x603498 0x60349c 0x6034a0 0x6034a4 0x6034a8 0x6034ac 0x6034b0 0x6034b4 0x6034b8 0x6034bc

0x603010: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0x603060: 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
0x6030b0: 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
0x603100: 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
0x603150: 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
0x6031a0: 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
0x6031f0: 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
0x603240: 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
0x603290: 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
0x6032e0: 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
0x603330: 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
0x603380: 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
0x6033d0: 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
0x603420: 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
0x603470: 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299

如您所见,多维数组在内存中相邻,没有两个内存地址重叠。甚至释放数组的例程也比为每个列(或行,取决于您如何查看数组)动态分配内存的标准方法简单。因为数组基本上由两个线性数组组成,所以只有这两个数组必须(并且可以)被释放。

该方法可以推广到具有相同概念的二维以上。我不会在这里做,但当你有了这个想法,这是一个简单的任务。

我希望这段代码对您的帮助和对我的帮助一样多。


尝试这样做:

1
2
3
int **ary = new int[sizeY];
for (int i = 0; i < sizeY; i++)
    ary[i] = new int[sizeX];


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

enter image description here

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#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;
}


如果您的项目是CLI(公共语言运行时支持),则:好的。

您可以使用数组类,而不是您在编写时得到的类:好的。

1
2
#include
using namespace std;

换句话说,当使用std名称空间和包含数组头时,不是得到的非托管数组类,不是std名称空间和数组头中定义的非托管数组类,而是cli的托管类数组。好的。

使用这个类,您可以创建任意等级的数组。好的。

下面的代码创建了2行3列的二维数组,类型为int,我将其命名为"arr":好的。

1
array<int, 2>^ arr = gcnew array<int, 2>(2, 3);

现在,您可以访问数组中的元素,按名称命名,只写一个带方括号的[],然后在其中添加行和列,并用逗号,分隔它们。好的。

下面的代码访问我在前面的代码中创建的数组的第2行和第1列中的元素:好的。

1
arr[0, 1]

只写这一行就是读取该单元格中的值,即获取该单元格中的值,但如果添加等号=符号,则将要在该单元格中写入值,即设置该单元格中的值。当然,您也可以使用+=、-=、*=和/=运算符,仅用于数字(int、float、double、uu int16、uu int32、uu int64等),但您肯定已经知道了。好的。

如果您的项目不是cli,那么您可以使用std名称空间的非托管数组类,当然,如果您是#include ,但是问题是这个数组类不同于cli数组。此类型的create数组与cli相同,只是必须删除^符号和gcnew关键字。但不幸的是,<>括号中的第二个int参数指定了数组的长度(即大小),而不是它的秩!好的。

在这种类型的数组中没有指定秩的方法,秩只是cli数组的特性。好的。

STD数组的行为类似于C++中的正常数组,用指针定义,例如EDCOX1,7,然后:EDCOX1,8,或没有指针:EDCOX1,9,但是,与C++的正常数组不同,STD数组提供了可以与数组元素一起使用的函数,如填充、开始、结束、大小等,但是正常数组不提供任何功能。好的。

但是STD数组还是一维数组,就像普通C++数组一样。但是,由于其他人建议如何将普通的C++一维数组转换成二维数组,我们可以将相同的思想应用到STD数组,例如根据Mehrdad Afshari的想法,我们可以编写以下代码:好的。

1
array, 2> array2d = array, 2>();

这一行代码创建了一个"可变数组",它是一个一维数组,每个单元格都是或指向另一个一维数组。好的。

如果一维数组中的所有一维数组的长度/大小都相等,则可以将array2d变量视为真正的二维数组,此外,还可以使用特殊方法来处理行或列,具体取决于您如何在std数组支持的二维数组中查看它。好的。

您还可以使用Kevin Loney的解决方案:好的。

1
2
3
4
int *ary = new int[sizeX*sizeY];

// ary[i][j] is then rewritten as
ary[i*sizeY+j]

但是,如果使用std数组,代码必须看起来不同:好的。

1
2
array<int, sizeX*sizeY> ary = array<int, sizeX*sizeY>();
ary.at(i*sizeY+j);

还有std数组的独特功能。好的。

注意,您仍然可以使用[]括号访问std数组的元素,并且不必调用at函数。您还可以定义和分配新的int变量,该变量将计算并保留std数组中的元素总数,并使用其值,而不是重复sizeX*sizeY。好的。

您可以定义自己的二维数组泛型类,并定义二维数组类的构造函数以接收两个整数,以指定新二维数组中的行数和列数,以及定义get函数,该函数接收两个整数参数,这些参数访问二维数组中的元素并返回它的值和接收三个参数的set函数,其中第一个参数是指定二维数组中的行和列的整数,第三个参数是元素的新值。它的类型取决于您在泛型类中选择的类型。好的。

你可以通过使用普通C++数组(指针或不带)或STD数组来实现这一点,并使用其他人建议的一种思想,使其易于使用CLI数组,或者类似于可以在C语言中定义、分配和使用的二维数组。好的。好啊。


首先使用指针(第1行)定义数组:

1
2
3
int** a = new int* [x];     //x is the number of rows
for(int i = 0; i < x; i++)
    a[i] = new int[y];     //y is the number of columns

这个答案的目的不是添加其他人还没有涵盖的新内容,而是扩展@kevin loney的答案。

您可以使用轻量级声明:

1
int *ary = new int[SizeX*SizeY]

访问语法为:

1
ary[i*SizeY+j]     // ary[i][j]

但这对大多数人来说是很麻烦的,而且会导致混乱。因此,可以定义如下宏:

1
#define ary(i, j)   ary[(i)*SizeY + (j)]

现在,您可以使用非常相似的语法ary(i, j) // means ary[i][j]访问数组。这具有简单美观的优点,同时,使用表达式代替索引也更简单、更不容易混淆。

例如,要访问ary[2+5][3+8],可以编写ary(2+5, 3+8),而不是复杂的ary[(2+5)*SizeY + (3+8)],即它保存了括号并有助于可读性。

Caveats:

  • 尽管语法非常相似,但它并不相同。
  • 如果将数组传递给其他函数,则必须使用相同的名称(或声明为全局变量)传递SizeY

或者,如果需要在多个函数中使用数组,那么可以在宏定义中添加sizey作为另一个参数,如下所示:

1
#define ary(i, j, SizeY)  ary[(i)*(SizeY)+(j)]

你明白了。当然,这会变得太长而无法使用,但它仍然可以防止混淆+和*。

这不是绝对推荐的,它会被大多数有经验的用户谴责为不好的做法,但我不能拒绝分享它,因为它的优雅。

P.S.:我已经测试过了,在G++14和G++11编译器上,相同的语法(左值和右值)都可以工作。


我使用了这个不优雅,但快速,容易和工作系统。我不明白为什么不能工作,因为系统允许创建大尺寸阵列和访问部件的唯一方法是不将其部分切割:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#define DIM 3
#define WORMS 50000 //gusanos

void halla_centros_V000(double CENW[][DIM])
{
    CENW[i][j]=...
    ...
}


int main()
{
    double *CENW_MEM=new double[WORMS*DIM];
    double (*CENW)[DIM];
    CENW=(double (*)[3]) &CENW_MEM[0];
    halla_centros_V000(CENW);
    delete[] CENW_MEM;
}

在某些情况下,我留给你的解决方案对我来说是最好的。尤其是如果你知道[的大小?]数组的一维。对于字符数组非常有用,例如,如果我们需要一个大小不同的字符数组[20]。

1
2
3
4
5
6
7
8
int  size = 1492;
char (*array)[20];

array = new char[size][20];
...
strcpy(array[5],"hola!");
...
delete [] array;

键是数组声明中的括号。


动态声明二维数组:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
    #include<iostream>
    using namespace std;
    int main()
    {
        int x = 3, y = 3;

        int **ptr = new int *[x];

        for(int i = 0; i<y; i++)
        {
            ptr[i] = new int[y];
        }
        srand(time(0));

        for(int j = 0; j<x; j++)
        {
            for(int k = 0; k<y; k++)
            {
                int a = rand()%10;
                ptr[j][k] = a;
                cout<<ptr[j][k]<<"";
            }
            cout<<endl;
        }
    }

现在,在上面的代码中,我们取了一个双指针,给它分配了一个动态内存,并给出了列的值。这里分配的内存只用于列,现在对于行,我们只需要一个for循环,并为每一行分配一个动态内存值。现在我们可以像使用二维数组那样使用指针。在上面的例子中,我们将随机数分配给我们的二维数组(指针),这一切都是关于二维数组的dma。


我在创建动态数组时使用它。如果有类或结构。这是可行的。例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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;
  }

这不是一个在很多细节,但相当简单。

1
2
3
4
int *arrayPointer = new int[4][5][6]; // ** LEGAL**
int *arrayPointer = new int[m][5][6]; // ** LEGAL** m will be calculated at run time
int *arrayPointer = new int[3][5][]; // ** ILLEGAL **, No index can be empty
int *arrayPointer = new int[][5][6]; // ** ILLEGAL **, No index can be empty

记得:

1。只有第一个索引可以是运行时变量。其他索引必须是常量

2。索引不能为空。

如其他答案所述,请致电

1
delete arrayPointer;

当您完成对数组的处理后,释放与数组关联的内存。