Mar*_*les 13 c++ arrays pointers multidimensional-array dynamic-arrays
我是C/C++的新手,我一直在讨厌,但仍然不知道如何制作这样的"结构"
它应该是一个使用指针的3D动态数组.
我这样开始,但卡在那里
int x=5,y=4,z=3;
int ***sec=new int **[x];
Run Code Online (Sandbox Code Playgroud)
知道如何使其成为y和z的静态大小就足够了;
拜托,我很感激你的帮助.
提前致谢.
Man*_*kla 21
要动态创建3D整数数组,最好先了解1D和2D数组.
1D阵列:你可以很容易地做到这一点
const int MAX_SIZE=128;
int *arr1D = new int[MAX_SIZE];
Run Code Online (Sandbox Code Playgroud)
在这里,我们创建一个int指针,指向可以存储整数的内存块.
2D数组:您可以使用上述1D数组的解来创建2D数组.首先,创建一个指向内存块的指针,其中只保存其他整数指针,最终指向实际数据.由于我们的第一个指针指向一个指针数组,所以这将被称为指针指针(双指针).
const int HEIGHT=20;
const int WIDTH=20;
int **arr2D = new int*[WIDTH]; //create an array of int pointers (int*), that will point to
//data as described in 1D array.
for(int i = 0;i < WIDTH; i++){
arr2D[i] = new int[HEIGHT];
}
Run Code Online (Sandbox Code Playgroud)
3D阵列:这就是你想要做的.在这里,您可以尝试上述两种情况中使用的方案.应用与2D阵列相同的逻辑.有问题的图解释了所有.第一个数组将是指向指针的指针(int*** - 因为它指向双指针).解决方案如下:
const int X=20;
const int Y=20;
const int z=20;
int ***arr3D = new int**[X];
for(int i =0; i<X; i++){
arr3D[i] = new int*[Y];
for(int j =0; j<Y; j++){
arr3D[i][j] = new int[Z];
for(int k = 0; k<Z;k++){
arr3D[i][j][k] = 0;
}
}
}
Run Code Online (Sandbox Code Playgroud)
jus*_*tin 11
// one-liner
typedef std::vector<std::vector<std::vector<int> > > ThreeDimensions;
// expanded
typedef std::vector<int> OneDimension;
typedef std::vector<OneDimension> TwoDimensions;
typedef std::vector<TwoDimension> ThreeDimensions;
Run Code Online (Sandbox Code Playgroud)
(毕竟这是标记的c ++)
编辑以回应乔的问题
你好再次乔=)肯定.这是一个例子:
#include <vector>
#include <iostream>
int main(int argc, char* const argv[]) {
/* one-liner */
typedef std::vector<std::vector<std::vector<int> > >ThreeDimensions;
/* expanded */
typedef std::vector<int>OneDimension;
typedef std::vector<OneDimension>TwoDimensions;
typedef std::vector<TwoDimensions>ThreeDimensions;
/*
create 3 * 10 * 25 array filled with '12'
*/
const size_t NElements1(25);
const size_t NElements2(10);
const size_t NElements3(3);
const int InitialValueForAllEntries(12);
ThreeDimensions three_dim(NElements3, TwoDimensions(NElements2, OneDimension(NElements1, InitialValueForAllEntries)));
/* the easiest way to assign a value is to use the subscript operator */
three_dim[0][0][0] = 11;
/* now read the value: */
std::cout << "It should be 11: " << three_dim[0][0][0] << "\n";
/* every other value should be 12: */
std::cout << "It should be 12: " << three_dim[0][1][0] << "\n";
/* get a reference to a 2d vector: */
TwoDimensions& two_dim(three_dim[1]);
/* assignment */
two_dim[2][4] = -1;
/* read it: */
std::cout << "It should be -1: " << two_dim[2][4] << "\n";
/* get a reference to a 1d vector: */
OneDimension& one_dim(two_dim[2]);
/* read it (this is two_dim[2][4], aka three_dim[1][2][4]): */
std::cout << "It should be -1: " << one_dim[4] << "\n";
/* you can also use at(size_t): */
std::cout << "It should be 12: " << one_dim.at(5) << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)