假设我有一个数组:
double theArray[2][5][3][4];
我不太明白最后一个维度。
first is [][][][][]
second is [][][][][]
[][][][][]
third would make it 3 dimensional,
第四个人会怎么做?
c++(就像之前的C)并没有真正的多维数组,所以它们都不是真正的2、3、4(等等)维。
相反,c++提供的是数组、数组的数组等。有了四组括号,你就有了一个数组的数组的数组的数组。
现在,忘记我说的那些——在c++中使用数组很少是一个好主意,使用数组的数组通常更糟糕。如您上面所示的伪4d数组还要糟糕很多倍。别这么做。
如果需要模拟2D、3D等数组,请使用类。
第四个维度是时间。它与三个空间维度一起形成时空
double theArray[2] ==> [][]
double theArray[2][5] ==> [][], [][], [][], [][], [][]
double theArray[2][5][3] ==> [][], [][], [][], [][], [][]
[][], [][], [][], [][], [][]
[][], [][], [][], [][], [][]
double theArray[2][5][3][4] ==> .............
在C和c++中,二维数组都是数组的数组——不多不少。
三维数组是数组的数组的数组
你有什么:
double theArray[2][5][3][4];
是一个四维数组,是数组的数组的数组的数组。
如果你考虑的是空间维度,那么数组的任何维度都不一定有任何物理意义。它们是元素的简单有序序列,其中序列本身可以是序列,等等。
数组的维数没有限制(除了编译时和运行时存储空间,可能是编译器强加的一些任意限制)。
对于一个二维数组,你可以把元素想象成一个矩形网格:
[][][][]
[][][][]
[][][][]
,但实际上整个事情是线性的,每一行都紧跟着内存中的前一行。
[][][][][][][][][][][][]
- row0 -- row1- - row2 -
您还可以构建像多维数组一样的其他数据结构。如果使用指针、指针数组等等,那么元素和行可能会在内存中任意分散。但在大多数情况下,这并不重要。
comp.lang.c FAQ的第6节很好地讨论了C中经常令人困惑的数组和指针之间的关系,其中大部分也适用于c++。
c++提供了其他数据结构,作为标准库的一部分,它们比C风格的数组更灵活、更健壮。
如果你想要一个技巧来可视化什么是四维数组(数学术语是四维矩阵),你可以把它表示为立方体数组(如果维度不相等,更准确的说是矩形平行六面体)。
就像三维数组可以表示为矩阵的数组
假设我们想使用多维数组来跟踪世界人口。
// Population per country:
int population[ C ];
// the 1st dimension is the country index, C is the number of countries
// Population per country per state:
int population[ C ][ S ];
// the 2nd dimension is the state index, S is the max number of states per cuntry
// Population per country per state per county:
int population[ C ][ S ][ N ];
// the 3rd dimension is the county index, N is the max number of county per state
// Population per country per state per county per city:
int population[ C ][ S ][ N ][ I ];
// the 4th dimension is the city index, I is the max number of city per county
// Population per country per state per county per city per gender
// Population per country per state per county per city per gender per age-group
注意:这只是一个例子,它肯定不是最好的方法来模拟人口。