什么是锯齿状阵列?

ACP*_*ACP 44 c# jagged-arrays

什么是锯齿状数组(在c#中)?任何例子,什么时候应该使用它....

Ant*_*ram 55

锯齿状数组是一个数组数组.

string[][] arrays = new string[5][];
Run Code Online (Sandbox Code Playgroud)

这是五个不同的字符串数组的集合,每个字符串数组可以是不同的长度(它们也可以是相同的长度,但重点是它们不能保证它们).

arrays[0] = new string[5];
arrays[1] = new string[100];
...
Run Code Online (Sandbox Code Playgroud)

这与2D数组不同,它是矩形的,意味着每行具有相同的列数.

string[,] array = new string[3,5];
Run Code Online (Sandbox Code Playgroud)

  • 确切地说,内部数组不一定*都是相同的长度; 他们很可能会.将多维数组实现为锯齿状数组实际上很常见. (2认同)

Tar*_*rka 10

锯齿状数组在任何语言中都是相同的,但它是在第二个和超出数组中具有不同数组长度的2维数组的地方.

[0] - 0, 1, 2, 3, 4
[1] - 1, 2, 3
[2] - 5, 6, 7, 8, 9, 10
[3] - 1
[4] - 
[5] - 23, 4, 7, 8, 9, 12, 15, 14, 17, 18
Run Code Online (Sandbox Code Playgroud)


Aay*_*ain 6

尽管问题所有者选择了最佳答案,但我仍然希望提供以下代码以使锯齿状数组更清晰.

using System;

class Program
{
static void Main()
 {
 // Declare local jagged array with 3 rows.
 int[][] jagged = new int[3][];

 // Create a new array in the jagged array, and assign it.
 jagged[0] = new int[2];
 jagged[0][0] = 1;
 jagged[0][1] = 2;

 // Set second row, initialized to zero.
 jagged[1] = new int[1];

 // Set third row, using array initializer.
 jagged[2] = new int[3] { 3, 4, 5 };

 // Print out all elements in the jagged array.
 for (int i = 0; i < jagged.Length; i++)
  {
    int[] innerArray = jagged[i];
    for (int a = 0; a < innerArray.Length; a++)
    {
    Console.Write(innerArray[a] + " ");
    }
    Console.WriteLine();
  }
 }
}
Run Code Online (Sandbox Code Playgroud)

输出将是

1 2

0

3 4 5
Run Code Online (Sandbox Code Playgroud)

锯齿状数组用于以不同长度的行存储数据.

有关更多信息,请在MSDN博客上查看此帖子.


Tar*_*rik 5

您可以在此处找到更多信息:http://msdn.microsoft.com/en-us/library/2s05feca.aspx

另外:

锯齿状数组是一个数组,其元素是数组.锯齿状阵列的元素可以具有不同的尺寸和大小.锯齿状数组有时被称为"数组数组".以下示例显示如何声明,初始化和访问锯齿状数组.

以下是具有三个元素的一维数组的声明,每个元素都是一个整数的一维数组:

jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
Run Code Online (Sandbox Code Playgroud)

要么

jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };
Run Code Online (Sandbox Code Playgroud)