为什么我们有两个交错数组和多维数组?数组、多维、有两个

2023-09-02 01:33:17 作者:Peoples favorite(万众宠爱)

嗯,这可能是非常基本的问题(我觉得杀我)......但

什么是交错数组和多维数组之间的差异。 有一个在另一个的好处?

和为什么会在Visual Studio不允许我做了

  MyClass的[] [] ABC =新MyClass的[10] [20];
 

(我们用来做,在C ++,但在C#它强调[20]用红色wriggly行..说无效排名符)​​

但高兴与

  MyClass的[,] ABC =新MyClass的[10,20]。
 
多维数组什么意思

最后,我怎么能初始化这一行(就像我们做简单的数组与 {新的XXX ...} {新的XXX ....}

  MyClass的[] [] [,] itemscollection;
 

解决方案

一个交错数组是一个数组,数组的-,所以一个 INT [] [] 是一个数组 INT [] ,其中每一个可以是不同长度的,并占据其自己的块在存储器中。多维数组( INT [,] )是一个单独的内存块(本质上是一个矩阵)。

您不能创建一个 MyClass的[10] [20] ,因为每个子阵列必须单独初始化,因为它们是独立的对象:

  MyClass的[] [] ABC =新MyClass的[10] [];

的for(int i = 0; I< abc.Length;我++){
    ABC [我] =新MyClass的[20]。
}
 

MyClass的[10,20] 是确定的,因为它正在初始化一个对象为10行和20列的矩阵

A MyClass的[] [] [,] 可initailized像这样(不编译尽管测试):

  MyClass的[] [] [,] ABC =新MyClass的[10] [,] [,]

的for(int i = 0; I< abc.Length;我++){
    ABC [我] =新MyClass的[20,30] [,]

    为(诠释J = 0; J&其中; ABC [I] .GetLength(0); J ++){
        为(中间体K = 0; K&其中; ABC [I] .GetLength(1); k ++){
            ABC [I] [J,K] =新MyClass的[40,50]。
        }
    }
}
 

记住,CLR的是大量的一维数组访问进行了优化,所以采用交错数组可能会比同样大小的多维数组更快。

Well this may be very basic question (I feel like killing myself)... But

What is the difference between jagged array and Multidimensional array. Is there a benefit of one on another?

And why would the Visual Studio not allow me to do a

MyClass[][] abc = new MyClass[10][20];

(We used to do that in C++, but in C# it underlines [20] with red wriggly line.. Says invalid rank specifier)

but is happy with

MyClass[,] abc = new MyClass[10,20];

Finally how can I initialize this in a single line (like we do in simple array with {new xxx...}{new xxx....})

MyClass[][,][,] itemscollection;

解决方案

A jagged array is an array-of-arrays, so an int[][] is an array of int[], each of which can be of different lengths and occupy their own block in memory. A multidimensional array (int[,]) is a single block of memory (essentially a matrix).

You can't create a MyClass[10][20] because each sub-array has to be initialized separately, as they are separate objects:

MyClass[][] abc = new MyClass[10][];

for (int i=0; i<abc.Length; i++) {
    abc[i] = new MyClass[20];
}

a MyClass[10,20] is ok because it is initializing a single object as a matrix with 10 rows and 20 columns

A MyClass[][,][,] can be initailized like so (not compile tested though):

MyClass[][,][,] abc = new MyClass[10][,][,];

for (int i=0; i<abc.Length; i++) {
    abc[i] = new MyClass[20,30][,];

    for (int j=0; j<abc[i].GetLength(0); j++) {
        for (int k=0; k<abc[i].GetLength(1); k++) {
            abc[i][j,k] = new MyClass[40,50];
        }
    }
}

Bear in mind that the CLR is heavily optimized for single-dimension array access, so using a jagged array will likely be faster than a multidimensional array of the same size.