三维阵列动态分配问题

problem in dynamic allocation of 3-dimensional array

本文关键字:问题 动态分配 阵列 三维      更新时间:2023-10-16
array_2D = new ushort * [nx];
// Allocate each member of the "main" array
//
for (ii = 0; ii < nx; ii++)
    array_2D[ii] = new ushort[ny];
// Allocate "main" array
array_3D = new ushort ** [numexp];
// Allocate each member of the "main" array
   for(kk=0;kk<numexp;kk++)
       array_3D[kk]= new ushort * [nx];
   for(kk=0;kk<numexp;kk++)
       for(ii=0;ii<nx;ii++)
           array_3D[kk][ii]= new ushort[ny];

numexp,nx和ny的值由用户获取..

这是3d数组动态分配的正确形式....我们知道代码适用于2D数组…如果这是不正确的,谁能建议一个更好的方法?

我认为分配和处理多维数组的最简单方法是使用一个大的一维数组(或者最好是std::vector),并提供一个接口来正确索引。

这是最容易在二维空间中考虑的。考虑一个带有"x"answers"y"轴的二维数组

<>之前X =0 1 2Y =0 a b c我很高兴见到你。2 g h I之前

我们可以用一维数组来表示,重新排列如下:

<>之前Y = 0 0 0 1 1 1 2 2 2X = 0 1 2 0 1 2 0 1 2数组:a b c d f h I之前

那么我们的2d数组就是

   unsigned int maxX = 0;
   unsigned int maxY = 0;
   std::cout << "Enter x and y dimensions":
   std::cin << maxX << maxY
   int array = new int[maxX*maxY];
   // write to the location where x = 1, y = 2
   int x = 1;
   int y = 2;
   array[y*maxX/*jump to correct row*/+x/*shift into correct column*/] = 0;

最重要的是将访问打包成一个简洁的接口,这样你只需要弄清楚一次

以类似的方式,我们可以处理3d数组 <>之前Z = 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2Y = 0 0 0 1 1 1 2 2 0 0 0 1 1 1 0 0 1 1 1 2 2 2X = 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2数组:a/b/b/b/b/b/b/b/b/b/b/b/b/b/b/b/b/b/b/b/b/b之前

一旦你弄清楚了如何正确地索引到数组,并把这段代码放在一个公共的地方,你就不必处理指针指向指针数组的指针指向指针数组的指针的麻烦了。您只需要在最后执行一次delete[]。

看起来也不错,只要arr[numexp][nx][ny]的数组是你想要的。
一个小提示:你可以把第三维度的分配放到第二次维度的循环中,也就是说,在分配父子数组的同时分配每个第三维度:

ushort*** array_3D = new ushort**[nx];
for(int i=0; i<nx; ++i){
  array_3D[i] = new ushort*[ny];
  for(int j=0; j<ny; ++j)
    array_3D[i][j] = new ushort[nz];
}

当然,一般的提示是:对std::vectors这样做是为了不必处理讨厌的(de)分配问题。:)

#include <vector>
int main(){
  using namespace std;
  typedef unsigned short ushort;
  typedef vector<ushort> usvec;
  vector<vector<usvec> > my3DVector(numexp, vector<usvec>(nx, vector<ushort>(ny)));
//           size of -- dimension 1 ^^^^^^ -- dimension 2 ^^ --- dimension 3 ^^
}