首頁  >  文章  >  後端開發  >  C# 中的二維數組

C# 中的二維數組

王林
王林原創
2024-09-03 15:11:45220瀏覽

二維數組是跨越多個行和列的同質元素的集合,採用矩陣的形式。下面是一個 2D 陣列的範例,它有 m 行和 n 列,從而建立一個 m x n 配置的矩陣。

[ a1, a2, a3, a4, ..., an
b1, b2, b3, b4, ..., bn
c1, c2, c3, c4, ..., cn
.
.
.
m1, m2, m3, m4, ..., mn ]

鋸齒狀數組的概念

鋸齒數組是數組的數組。交錯數組本質上是多個數組交錯在一起形成多維數組。二維鋸齒狀數組可能看起來像這樣:

[ [ a1, a2, a3, a4, ..., an ],
[ b1, b2, b3, b4, ..., b20 ],
[ c1, c2, c3, c4, ..., c30 ],
.
.
.
[ m1, m2, m3, m4, ..., m25 ] ]

請注意,鋸齒狀陣列的所有行可能包含或不包含相同數量的元素。

真正的二維數組與鋸齒狀數組

從實現的角度來看,鋸齒數組與真正的二維數組完全不同。了解 C# 如何實現多維數組和鋸齒數組非常重要。

程式語言在多維數組的實作上有所不同。一些程式語言(如 C、C++、C#、Fortran 等)支援真正的二維數組。雖然還有其他人使用數組數組(也稱為鋸齒狀數組)來模擬這種行為。那麼,真正的二維數組與鋸齒狀數組有何不同?

多維數組的兩種實作在儲存消耗方面是不同的。雖然真正的 2D 數組每行有 m 行 n 元素,但鋸齒狀數組可能有 m 行,每行具有不同數量的元素。這使得資料集的浪費空間最小化。因此,下面的鋸齒狀數組完全沒問題:

int[][] jagged array = [ [1, 2, 3, 4],
[5, 6, 7],
[8, 9] ]

如果相同的資料集要在真正的二維數組中實現,則會如下所示:

int[,] multiDimArray = [ 1, 2, 3, 4
5, 6, 7, 0
8, 9, 0, 0 ]

C# 中二維數組的運算

這裡,對二維陣列的一些操作如下:

1.構造 C# 二維陣列

讓我們看看如何在 C# 中宣告 2D 數組,以及如何在 C# 中不宣告 2D 陣列。

怎麼做?

C# 中真正的二維數組實作從數組宣告開始。如下圖所示:

int[,] arr2D;
string[,] arr2D_s;

定義中逗號的數量決定了陣列的維數。請注意,您不能在數組聲明中指定數組的大小。它必須在數組初始化期間完成。

如何不呢?

二維數組和鋸齒狀數組的實作很容易混淆。鋸齒狀數組聲明如下:

int[][] jagged array;

2.初始化 C# 二維陣列

下一步是初始化我們剛剛宣告的二維陣列。有多種方法可以做到這一點。

使用新運算子

arr2D = new int[2,3];                    //separate initialization
string[,] arr2D_s = new string[4,5];    //with declaration

使用值初始化

//without dimensions
arr2D = new int[,]{{1,2}, {3,4}, {5,6}};
//with declaration
arr2D_s = new string[2,2]{{"one","two"},{"three", "four"}};

沒有新幹員

Int[,] arr2D_a = {{1,2}, {3,4}, {5,6}, {7,8}};

3。從 C# 二維數組讀取元素

讀取單一元素

下一個操作是從二維數組讀取元素。由於二維數組是 m x n 元素的矩陣,因此每個元素都有指定的行索引和列索引組合。我們可以透過在下標中提供行索引和列索引來存取元素。範例如下:

int[,] arr2D_i = {{1,2}, {3,4}, {5,6}, {7,8}};
string arr2D_s = {{"one","two"},{"three", "four"}};
int val_i = arr2D_i[2,1];          //returns '6'
string val_s = arr2D_s[1,1];       //returns 'four'
注意- 行和列的索引從 0 開始。因此,索引位置 [0,0] 是陣列的第一個元素,[m-1, n-1] 是陣列的最後一個元素。

閱讀所有元素

但是,上面的方法為我們提供了數組中單一元素的值。我們如何遍歷整個陣列來讀取它的每個元素?簡單的解決方案是使用巢狀的 for/while 迴圈遍歷整個陣列。

代碼

using System;
public class Program
{
public static void Main()
{
int[,] arr2D_i = new int[3, 3]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
//reading all the elements through for loop
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write(arr2D_i[i, j] + "\t");
}
Console.WriteLine("\n");
}
}
}

輸出

C# 中的二維數組

GetLength() 方法

好的。但是,上面的範例僅在我事先知道數組中元素的數量時才有效。如果我的陣列是動態的怎麼辦?如何遍歷動態數組的所有元素? GetLength 方法來拯救我們。

int arr2D.GetLength(0); //傳回第一個維度(行)

int arr2D.GetLength(1); //回傳第二維(列)

代碼

using System;
public class Program
{
public static void Main()
{
int[,] arr2D_i = new int[3, 3]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
//reading all the elements through for loop
for (int i = 0; i < arr2D_i.GetLength(0); i++)
{
for (int j = 0; j < arr2D_i.GetLength(1); j++)
{
Console.Write(arr2D_i[i, j] + "\t");
}
Console.WriteLine("\n");
}
}
}

輸出

C# 中的二維數組

每個循環的力量

for-each 迴圈為陣列的每個元素執行一組指令。這是一個非常強大的循環機制,強烈建議使用,因為它比傳統的 for 迴圈更有效率。

代碼

using System;
public class Program
{
public static void Main()
{
string[,] arr2D_s = new string[3, 3]{{"one", "two", "three"}, {"four","five","six"}, {"seven","eight","nine"}};
//reading all the elements through foreach loop
foreach(var ele in arr2D_s)
{
Console.WriteLine(ele);
}
}
}

輸出

C# 中的二維數組

4.在 C# 二維陣列中插入元素

現在讓我們來看一個有關如何在 C# 二維數組中插入元素的範例。思路是遍歷數組的每個位置並為其賦值。

代碼

using System;
public class Program
{
public static void Main()
{
int[,] arr2D_i = new int[3, 3]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[,] squares = new int[3, 3];
int[,] cubes = new int[3, 3];
for (int i = 0; i < arr2D_i.GetLength(0); i++)
{
for (int j = 0; j < arr2D_i.GetLength(1); j++)
{
squares[i, j] = arr2D_i[i, j] * arr2D_i[i, j];
cubes[i, j] = squares[i, j] * arr2D_i[i, j];
}
}
Console.WriteLine("Squares\n");
DisplayArray(squares);
Console.WriteLine("\n\nCubes\n");
DisplayArray(cubes);
}
static void DisplayArray(int[, ] arr)
{
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{ Console.Write(arr[i, j] + "\t"); }
Console.WriteLine("\n");
}
}
}

Output

C# 中的二維數組

5. Update Elements in C# 2D Array

We will update our array to multiply each element with 2. The idea is to traverse each position of the array and update the value it holds.

Code

using System;
public class Program
{
public static void Main()
{
int[, ] arr2D_i = new int[3, 3]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Console.WriteLine("Original Array\n");
DisplayArray(arr2D_i);
for (int i = 0; i < arr2D_i.GetLength(0); i++)
{
for (int j = 0; j < arr2D_i.GetLength(1); j++)
{
arr2D_i[i, j] *= 2;
}
}
Console.WriteLine("\n\nUpdated Array (multiplied by 2)\n");
DisplayArray(arr2D_i);
}
static void DisplayArray(int[, ] arr)
{
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write(arr[i, j] + "\t");
}
Console.WriteLine("\n");
}
}
}

Output

C# 中的二維數組

6. Delete Elements in C# 2D Array

This is a tricky operation. It is not possible to delete a single element from a true C# 2D Array. Deleting a single element will disturb the dimensions of the array such that it would no longer be a matrix. C# does not allow that unless it is a jagged array.

So, what is the solution? Do we delete the entire row or the entire column? No, C# would not allow that as well. The array is fixed in size when declared or initialized. It has fix bytes of memory allocated. We cannot change that at run time.

The solution here is to create a new array without the elements that we want to delete.

Code

using System;
public class Program
{
public static void Main()
{
int[,] arr2D_i = new int[3, 3]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[,] new_array = new int[2,2];
Console.WriteLine("Original Array\n");
DisplayArray(arr2D_i);
int rowToDel = 2;
int colToDel = 2;
for (int i = 0; i < arr2D_i.GetLength(0); i++)
{
if(i==rowToDel)
continue;
for (int j = 0; j < arr2D_i.GetLength(1); j++)
{
if(j==colToDel)
continue;
new_array[i,j]=arr2D_i[i,j];
}
}
Console.WriteLine("\n\nArray after deleting elements\n");
DisplayArray(new_array);
}
static void DisplayArray(int[, ] arr)
{
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write(arr[i, j] + "\t");
}
Console.WriteLine("\n");
}
}
}

Output

C# 中的二維數組

Conclusion

Thus, we have seen how a 2D Array is implemented in C# and what are the various CRUD operations we can perform on it. We also learned the difference between a true 2D implementation and a jagged array. There are a lot more methods available in C# to assist the developers with working with Arrays at ease. Do check them out at the MSDN docs.

Recommended Articles

This is a guide to 2D Arrays in C#. Here we discuss the concept of jagged arrays along with operations on 2D arrays in C#. You may also look at the following articles to learn more-

  1. 2D Arrays in Java
  2. 2D Arrays In Python
  3. Arrays in C#
  4. Arrays in C++

以上是C# 中的二維數組的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:C# 中的數組下一篇:C# 中的數組