在C#中,多维数组是一种数据结构,它允许我们在单个变量中存储访问多个维度的数据。多维数组可以是矩形的,也就是说,每一行都有相同数量的列,或者是交错的,即数组的数组,每个子数组可以有不同的长度。在本文中,我们将详细探讨如何在C#中使用多维数组,并通过示例来加深理解。
矩形多维数组在C#中使用逗号分隔的索引来定义维度。最常见的矩形数组是二维数组,但你可以定义更多维度的数组。
C#// 声明一个二维整数数组,有2行3列
int[,] matrix = new int[2, 3];
// 初始化一个二维数组
int[,] predefinedMatrix = { { 1, 2, 3 }, { 4, 5, 6 } };
C#// 访问第一行第三列的元素
int element = predefinedMatrix[0, 2]; // 输出 3
// 修改第二行第二列的元素
predefinedMatrix[1, 1] = 10; // 将 5 改为 10
C#for (int i = 0; i < predefinedMatrix.GetLength(0); i++)
{
for (int j = 0; j < predefinedMatrix.GetLength(1); j++)
{
Console.Write(predefinedMatrix[i, j] + " ");
}
Console.WriteLine();
}
交错数组(也称为锯齿数组)是数组的数组。每个子数组可以有不同的长度,这是与矩形多维数组的主要区别。
C#// 声明一个交错数组
int[][] jaggedArray = new int[3][];
// 初始化交错数组的行
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };
C#// 访问第三行第一列的元素
int jaggedElement = jaggedArray[2][0]; // 输出 6
// 修改第二行第二列的元素
jaggedArray[1][1] = 10; // 将 5 改为 10
C#foreach (int[] row in jaggedArray)
{
foreach (int element in row)
{
Console.Write(element + " ");
}
Console.WriteLine();
}
让我们通过几个示例来看看如何在实际中使用多维数组。
C#using System;
class MatrixOperations
{
static void Main()
{
int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
// 转置矩阵
int[,] transpose = new int[3, 3];
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
transpose[j, i] = matrix[i, j];
}
}
// 打印转置矩阵
Console.WriteLine("Transpose of the matrix:");
for (int i = 0; i < transpose.GetLength(0); i++)
{
for (int j = 0; j < transpose.GetLength(1); j++)
{
Console.Write(transpose[i, j] + " ");
}
Console.WriteLine();
}
}
}
C#using System;
class DynamicJaggedArray
{
static void Main()
{
// 创建一个交错数组,包含用户指定数量的行
Console.WriteLine("Enter the number of rows:");
int rows = int.Parse(Console.ReadLine());
int[][] jaggedArray = new int[rows][];
for (int i = 0; i < jaggedArray.Length; i++)
{
Console.WriteLine($"Enter the number of columns for row {i + 1}:");
int cols = int.Parse(Console.ReadLine());
jaggedArray[i] = new int[cols];
for (int j = 0; j < cols; j++)
{
Console.WriteLine($"Enter the element at [{i}][{j}]:");
jaggedArray[i][j] = int.Parse(Console.ReadLine());
}
}
// 打印交错数组
Console.WriteLine("Jagged array elements:");
foreach (int[] row in jaggedArray)
{
foreach (int element in row)
{
Console.Write(element + " ");
}
Console.WriteLine();
}
}
}
多维数组是C#中非常强大的数据结构,它允许我们以结构化的方式存储和访问数据。矩形多维数组适用于需要规则数据结构的情况,而交错数组则为不规则数据提供了灵活性。通过上述示例,我们了解了如何声明、初始化、访问和遍历多维数组,以及如何将它们应用于实际编程问题。掌握多维数组是成为一名熟练的C#开发者的关键步骤之一。
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!