什么是锯齿数组(在C#中)?有没有示例以及何时应该使用它....
什么是锯齿数组(在C#中)?有没有示例以及何时应该使用它....
不规则数组是由数组组成的数组。
string[][] arrays = new string[5][];
这是五个不同的字符串数组集合,每个集合的长度可能不同(它们也可以是相同的长度,但重点是不能保证它们是相同的)。
arrays[0] = new string[5];
arrays[1] = new string[100];
...
这与二维数组不同,因为它是矩形的,也就是说每一行拥有相同数量的列。
string[,] array = new string[3,5];
锯齿数组在任何语言中都是相同的,但它指的是第二个及以后的维度中具有不同数组长度的二维或更高维数组。
[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
虽然最佳答案被问题所有者选中,但我仍然想提供以下代码,以使锯齿数组更清晰。
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();
}
}
}
1 2
0
3 4 5
锯齿状数组用于以长度不同的行存储数据。
欲了解更多信息,请查看MSDN博客上的这篇文章。
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
或者
jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };
嵌套数组是在声明期间声明行数,但在运行时或用户选择时声明列数的数组。简单来说,当您想要在每个不同的嵌套数组中拥有不同数量的列时,适合使用嵌套数组。
int[][] a = new int[6][];//its mean num of row is 6
int choice;//thats i left on user choice that how many number of column in each row he wanna to declare
for (int row = 0; row < a.Length; row++)
{
Console.WriteLine("pls enter number of colo in row {0}", row);
choice = int.Parse(Console.ReadLine());
a[row] = new int[choice];
for (int col = 0; col < a[row].Length; col++)
{
a[row][col] = int.Parse(Console.ReadLine());
}
}
嵌套数组是一个包含其他数组的数组。
嵌套数组是一种行数固定但列数不固定的数组。
C#窗体应用程序中嵌套数组的代码
int[][] a = new int[3][];
a[0]=new int[5];
a[1]=new int[3];
a[2]=new int[1];
int i;
for(i = 0; i < 5; i++)
{
a[0][i] = i;
ListBox1.Items.Add(a[0][i].ToString());
}
for(i = 0; i < 3; i++)
{
a[0][i] = i;
ListBox1.Items.Add(a[0][i].ToString());
}
for(i = 0; i < 1; i++)
{
a[0][i] = i;
ListBox1.Items.Add(a[0][i].ToString());
}
如您所见,上述程序中行数固定为3,但列数不固定。因此,我们取了三个不同的列值,即5、3和1。此代码中使用的ListBox1
关键字是用于在窗体中使用的列表框,以便通过单击按钮查看结果,该按钮也将在窗体中使用。这里完成的所有编程都是在按钮上进行的。
ListBox1.Items.Add(...)
就能完成吗?这会极大地拖慢算法的速度。所有操作都应该在处理器和内存之间进行,而不涉及用户界面。 - CodeArtist锯齿数组是具有不同行数的多维数组。