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

就像,对于“正常”数组我会:

int* ary = new int[Size]

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

a) 无法工作/编译,b) 无法完成:

int ary[sizeY][sizeX] 

做。

有帮助吗?

解决方案

一个动态2D阵列基本上是指针的数组,以阵列。可以使用一个循环,这样初始化:

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

以上,对于colCount= 5rowCount = 4,会产生以下:

“在这里输入的图像描述”

其他提示

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;

修改如迪特里希埃普在评论中指出这是不完全的轻重量的溶液。另一种方法将是使用存储器的一个大的块:

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

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

虽然这种普遍的回答会给你你想要的索引的语法,这是双重效率低下:大和空间都慢和时间。有一个更好的办法。

<强>为什么这个问题的答案是大和慢速

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

int val = matrix[ x ][ y ];

此工作,因为矩阵[X]返回一个指针数组,然后将其用[Y]索引。它分解:

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

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

但是,该溶液具有一个大的缺点下,即它是脂肪和缓慢的。

为什么?

究其原因,它的脂肪和慢其实是一样的。每“行”中的矩阵是一个单独分配的动态数组。制作堆分配既在时间和空间成本。分配器需要时间的分配,有时运行O(n)的算法来做到这一点。和分配器“垫”每个记账和对齐额外的字节你排阵列。这额外的空间费用......好额外的空间。该释放器将的,当你去解除分配矩阵,精心免费-ING了每个单排配置花费额外的时间。让我一身汗只是想着它。

还有另外一个原因,它的速度慢。这些独立的分配往往生活在记忆不连续的部分。一行可能是在地址1000,另一个地址100,000你的想法。这意味着,当你穿越矩阵,你通过记忆跳跃像野生的人。这往往会导致高速缓存未命中,你的处理时间大大减慢。

所以,如果你绝对必须有你的可爱[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会感谢你。

在C ++ 11它是可能的:

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

此方式中,存储器未初始化。对其进行初始化为此代替:

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

示例程序(编译用 “克++ -std = C ++ 11”):

#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;
}

输出:

2 4 
3 5 

0 0 
0 0 
double (*) [2]

我从你的静态数组例如假定你想要一个矩形阵列,而不是锯齿状的。可以使用以下内容:

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

然后,可以访问元素为:

ary[y*sizeX + x]

不要忘记使用删除[]上ary

有,我会建议这在C ++ 11和上面,一个用于编译时间维度和一个用于运行时两种通用技术。两个答案假设要均匀,二维阵列(未锯齿状的)。

编译时间维度

使用std::arraystd::array然后使用new把它放在堆:

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

再次,如果尺寸的大小是在编译时已知这仅适用。

运行时间维度

实现与仅在运行时已知的尺寸为2维阵列的最佳方式是将其包装成一个类。类将分配一个一维数组,然后过载operator []为第一尺寸提供索引。 这样做是因为在C ++的2D阵列是行优先:

(来自 HTTP摘自://埃利.thegreenplace.net / 2015 /存储器布局的-多维阵列/ )功能

的存储器中的连续序列是良好的性能方面的原因,并且还容易清理。这里省略了许多有用的方法,但示出了其基本思想的示例类:

#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[]>(rows * columns)条目的阵列。我们超载operator []这将索引行我们。它返回一个指向该行,然后可以解除引用作为正常的列比年初int *。注意,在C ++ 14 make_unique第一艘船,但如果需要的话可以填充工具它在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++ 中但不存在时,首先要查看的地方是 boost.org. 。在那里我找到了 Boost 多维数组库, multi_array. 。它甚至包括一个 multi_array_ref 可用于包装您自己的一维数组缓冲区的类。

为什么不使用STL:矢量?如此简单,你不需要删除矢量。

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上创建2,3(或多)维数组/ C ++?

:一种2D阵列基本上是指针,其中每个指针指向一维数组,这将保持的实际数据的一维数组。

下面,N是行和M是列。

<强>动态分配

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

<强>填

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

打印

for(int i = 0; i < N; i++)
    for(int j = 0; j < M; j++)
      std::cout << ary[i][j] << "\n";

<强>自由

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

如何分配在GNU C ++的连续多维数组?有一个GNU扩展,它允许“标准”语法来工作。

看来来自操作者新的[]中的问题。确保你使用的运营商,而不是新的:

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

而这一切:你得到一个C兼容多维数组...

的typedef是你的朋友

回去,看着许多其他的答案后,我发现一个更深层次的解释是为了,因为许多其他的答案无论是从性能问题的困扰或强迫你使用异常或繁重的语法来声明数组,或访问数组元素(或所有上述)。

首先,此答案假设你知道在编译时该阵列的尺寸。如果这样做,那么这是因为它都将提供最佳的解决方案 最佳的性能,并允许您使用标准数组语法访问数组元素

这提供了最好的性能的原因是因为它分配所有的阵列作为存储意味着你很可能有更少的分页落空,更好的空间局部性的连续块。在一个循环中分配可能导致单独的阵列到(可能多次)被其他线程或进程结束通过为分配循环可能被中断的虚拟内存空间散布在多个非连续的页面,或简单地因的酌分配小的,空的内存块填充它恰好有可用。

在其它益处是一个简单的声明的语法和标准阵列访问语法。

在C ++使用新:

#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风格:

#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;
}

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

#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 << "\n\n";

    // 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,输出将是如下:

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

可以看到,多维阵列在于连续在存储器中,并且没有两个存储器地址是重叠的。即使对于释放数组日常大于每单柱动态分配内存(或行,这取决于你如何看待阵列)的标准方法简单。由于阵列基本上由两个线性阵列中,只有这两个必须是(可以)被释放。

此方法可以被扩展为多于两个的维度具有相同的概念。我不会做在这里,但是当你得到它背后的想法,这是一个简单的任务。

我希望这个代码将帮助您尽可能多地帮助了我。

尝试这样做的:

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

这个答案的目的不是添加其他人尚未涵盖的任何新内容,而是扩展@Kevin Loney 的答案。

您可以使用轻量级声明:

int *ary = new int[SizeX*SizeY]

访问语法将是:

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

但这对于大多数人来说很麻烦,并且可能会导致混乱。因此,您可以定义一个宏,如下所示:

#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)] IE。它节省了括号并有助于提高可读性。

注意事项:

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

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

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

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

绝对不推荐这样做,并且大多数有经验的用户都会谴责这是不好的做法,但由于它的优雅,我无法抗拒分享它。

附:我已经对此进行了测试,并且相同的语法可以在 g++14 和 g++11 编译器上工作(作为左值和右值)。

在这里,我有两种选择。第一个显示阵列或指针的指针数组的概念。我喜欢第二个,因为这些地址是连续的,因为你可以在图像中看到。

“在这里输入的图像描述”

#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(公共语言运行库支持),然后:

您可以使用数组类,而不是一个当你写你:

#include <array>
using namespace std;

在换言之,并非非托管数组类您使用std命名空间和包括阵列头,而不是在std命名空间和在阵列头中定义的非托管数组类时,当得到,但CLI的托管类阵列

这个类中,可以创建任何的秩的阵列要。

下面下面的代码创建新的2行二维阵列和3列和int类型的,我将其命名为“ARR”:

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

现在可以访问的元件阵列中,由命名为和写入的仅一个平方括号[],并且在其内部,添加的行和列,并将它们与逗号,分离。

下面的代码下面的访问在第二行和我已经在上面先前代码创建的阵列的第一列中的元素:

arr[0, 1]

只写此行是读取该小区,即价值得到该单元格的值,但如果添加等于=标志,您要在该单元格中写入值,即在此设置的值细胞。 您也可以使用+ =, - =,* =和/ =当然,运营商,换号只(整型,浮点,双,__int16,__int32,__int64和等),但相信你已经知道了。

如果你的项目的不可以 CLI,那么你可以使用非托管数组类std命名空间,如果你#include <array>,当然,但问题是,这个数组类是比CLI不同阵列。创建这种类型的数组是同一类的CLI,但你将不得不删除^符号和gcnew关键字。但不幸的是在括号<>第二INT参数指定的长度(即尺寸)的阵列的下,的它的秩!

有没有办法在这种阵列的指定秩,秩是CLI阵列的特征的

STD阵列的行为类似于在C + +正常阵列,你定义与指针,例如int*然后:new int[size],或没有指针:int arr[size],但C ++的标准阵列不同,STD阵列提供了可与使用的功能数组的元素,如填充,开始,结束,大小,和等,但正常阵列提供的没有

但是仍然STD阵列是一个维阵列,象普通的C ++阵列。 但是,这要归功于其他人建议有关如何可以让普通的C ++一个维数组二维数组的解决方案,我们能够适应同样的想法到std阵列,例如根据迈赫达德Afshari的想法,我们可以写出如下代码:

array<array<int, 3>, 2> array2d = array<array<int, 3>, 2>();

这行代码创建的“jugged阵列” 下,这是一个一个维阵列,每个其细胞中是或点到另一个一个维阵列。

如果在一个维阵列中的所有一个维数组是在它们的长度/大小相等,那么就可以治疗array2d变量作为一个真正的二维阵列,加上可以使用特殊的方法来治疗的行或列,取决于如何您注意查看,2D阵列中,该STD阵列支持。

您也可以使用凯文·Loney的解决方案:

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

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

但是如果使用std阵列,代码必须看起来不同:

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

和仍然有在std阵列的独特功能。

请注意,您仍然可以使用[]括号访问STD数组中的元素,而不必调用at功能。 您也可以定义和分配新的int变量,将计算并保持STD数组中元素的总数,并使用它的价值,而不是重复sizeX*sizeY

您可以定义自己的二维数组泛型类,并定义二维数组类的构造函数接收两个整数指定新的二维阵列中的行数和列数,并定义拿到收到两个功能整数的参数,所述二维阵列中访问一个元素,并返回它的值,以及接收三个参数设定功能,即两个第一是指定所述二维阵列中的行和列的整数,和第三个参数是新的该元素的值。它的类型取决于您在泛型类选择的类型。

您将能够通过使用的或者常规的C ++阵列(指针或不加)在std阵列来实现这一切和使用的想法,其他人一个建议的,并且可以很容易地像CLI数组使用,或类似二维阵列可以定义,分配和在C#使用。

通过使用指针(1号线),其限定所述阵列开始:

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

我已经离开你与工作最适合我的,在某些情况下的解决方案。特别是,如果一个人知道[大小η]阵列中的一个维度。为字符数组非常有用的,例如,如果我们需要改变字符的阵列的尺寸的阵列[20]。

int  size = 1492;
char (*array)[20];

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

的关键是在该阵列声明的括号中。

我用这个不优雅,但快速,方便和工作系统。我不明白为什么不能工作,因为该系统允许创建一个大尺寸的阵列和接入部分的唯一方法就是不削减它在部分:

#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;
}

下面的实施例可以帮助,

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;
}

动态声明2D阵列:

    #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循环和分配的每一行动态内存的值。现在我们可以使用指针只是我们使用了一个二维数组的方式。在上面的例子中,我们然后被分配的随机数到我们的2D阵列(指针)。其所有关于2D阵列的DMA。

我创建动态数组时使用此。如果你有一个类或结构。这一点也适用。例如:

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;
  } 

这是不是一个在许多细节,但相当简化。

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。 NO INDEX可以留空。

正如在其他的答案中提到,呼叫

delete arrayPointer;
当你与阵列做

解除分配与阵列相关联的存储器。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top