C#—交错数组
C#—交错数组
在C#中,交错数组是一个数组的数组,其中每个元素数组的长度可以不同。交错数组通常使用 jagged array 来表示。
声明实例化:
int[][] jaggedArrayOne = new int[2][]; // 实例化// 初始化
int[][] jaggedArrayTwo = new int[5][] { new int[] { 5 },new int[] { 4, 7 },new int[] { 5, 3, 1 },new int[] { 2, 4, 4, 1 },new int[] { 7, 5, 3, 2, 4 }};// 如果声明的同时初始化,必须要有5个数组
赋值
arr1[0] = new int[] { 7, 5, 3, 2, 4 };
访问个别数组元素:
// Assign 77 to the second element ([1]) of the first array ([0]):
jaggedArray3[0][1] = 77;// Assign 88 to the second element ([1]) of the third array ([2]):
jaggedArray3[2][1] = 88;
混合多为数组使用
可以混合使用交错数组和多维数组。 下面声明和初始化一个一维交错数组,该数组包含大小不同的三个二维数组元素。 有关二维数组的详细信息,请参阅多维数组(C# 编程指南)。
int[][,] jaggedArray4 = new int[3][,]
{new int[,] { {1,3}, {5,7} },new int[,] { {0,2}, {4,6}, {8,10} },new int[,] { {11,22}, {99,88}, {0,9} }
};// 可以如本例所示访问个别元素,该示例显示第一个数组的元素 [1,0] 的值(值为 5):
System.Console.Write("{0}", jaggedArray4[0][1, 0]);// 方法 Length 返回包含在交错数组中的数组的数目。 例如,假定已声明了前一个数组,则此行:
System.Console.WriteLine(jaggedArray4.Length);
示例
using System;class Program
{static void Main(){// 创建一个包含3个元素的交错数组,每个元素是一个整型数组int[][] jaggedArray = new int[3][];// 给交错数组的元素赋值jaggedArray[0] = new int[5]; // 第一个元素是一个长度为5的数组jaggedArray[1] = new int[4]; // 第二个元素是一个长度为4的数组jaggedArray[2] = new int[2]; // 第三个元素是一个长度为2的数组// 填充数组元素for (int i = 0; i < jaggedArray.Length; i++){for (int j = 0; j < jaggedArray[i].Length; j++){jaggedArray[i][j] = i + j;}}// 打印交错数组的内容for (int i = 0; i < jaggedArray.Length; i++){Console.WriteLine($"Element {i}:");for (int j = 0; j < jaggedArray[i].Length; j++){Console.Write($"{jaggedArray[i][j]} ");}Console.WriteLine();}}
}
C#中交错数组和二维数组的差别
在C#中,交错数组(Jagged Array)是一个元素为数组的数组,而二维数组(Multidimensional Array)是一个具有行和列的矩阵。交错数组的每个子数组可以有不同的长度,而二维数组的每行都必须具有相同的列数。