>  기사  >  백엔드 개발  >  C#의 2D 배열

C#의 2D 배열

王林
王林원래의
2024-09-03 15:11:45220검색

2차원 배열은 행렬 형태를 가정하여 여러 행과 열에 걸쳐 있는 동종 요소의 모음입니다. 다음은 m개의 행과 n개의 열이 있어 m x n 구성의 행렬을 생성하는 2D 배열의 예입니다.

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

재기드 배열의 개념

Jagged Array는 배열의 배열입니다. 가변 배열은 본질적으로 다차원 배열을 형성하기 위해 함께 가변된 여러 배열입니다. 2차원 들쭉날쭉한 배열은 다음과 같습니다.

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

가변 배열의 모든 행에는 동일한 수의 요소가 포함될 수도 있고 포함되지 않을 수도 있습니다.

진정한 2D 배열과 가변 배열

Jagged Array는 구현 관점에서 실제 2D 배열과 완전히 다릅니다. C#에서 다차원 배열과 가변 배열을 모두 구현하는 방법을 이해하는 것이 중요합니다.

프로그래밍 언어는 다차원 배열 구현이 다릅니다. C, C++, C#, Fortran 등과 같은 일부 프로그래밍 언어는 진정한 2D 배열을 지원합니다. 배열 배열(일명 들쭉날쭉한 배열)을 사용하여 이 동작을 시뮬레이션하는 다른 방법도 있습니다. 그렇다면 실제 2차원 배열은 들쭉날쭉한 배열과 어떻게 다릅니까?

다차원 배열의 두 가지 구현은 스토리지 소비 측면에서 다릅니다. 실제 2D 배열에는 각각 n개의 요소로 구성된 m개의 행이 있지만, 들쭉날쭉한 배열에는 각각 서로 다른 수의 요소가 있는 m개의 행이 있을 수 있습니다. 이는 데이터 세트에 대해 낭비되는 공간을 최소화합니다. 따라서 아래의 들쭉날쭉한 배열은 완벽하게 괜찮습니다.

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

동일한 데이터 세트를 실제 2D 배열로 구현한다면 아래와 같을 것입니다.

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

C#의 2D 배열 작업

아래에는 2D 배열에 대한 일부 작업이 나와 있습니다.

1. C# 2D 배열 구성

C#에서 2차원 배열을 선언하는 방법과 C#에서 2차원 배열을 선언하지 않는 방법을 살펴보겠습니다.

방법

C#의 진정한 2D 배열 구현은 배열 선언으로 시작됩니다. 아래와 같습니다:

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

정의의 쉼표 수에 따라 배열의 크기가 결정됩니다. 배열 선언에서는 배열의 크기를 지정할 수 없습니다. 이는 배열 초기화 중에 수행되어야 합니다.

어떻게 하지 않을 수 있나요?

2D 배열 구현과 들쭉날쭉한 배열을 혼동하기 쉽습니다. 들쭉날쭉한 배열 선언은 다음과 같습니다.

int[][] jagged array;

2. C# 2D 배열 초기화

다음 단계는 방금 선언한 2D 배열을 초기화하는 것입니다. 여러 가지 방법이 있습니다.

새 연산자 사용

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# 2D 배열에서 요소 읽기

단일 요소 읽기

다음 작업은 2D 배열에서 요소를 읽는 것입니다. 2D 배열은 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#의 2D 배열

GetLength() 메서드

알겠습니다. 하지만 위의 예는 배열의 요소 수를 미리 알고 있는 경우에만 작동합니다. 내 배열이 동적이면 어떻게 되나요? 동적 배열의 모든 요소를 ​​어떻게 탐색합니까? 여기에 GetLength 메서드가 있습니다.

int arr2D.GetLength(0); //1차원(행) 반환

int arr2D.GetLength(1); //2차원(열) 반환

코드

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#의 2D 배열

각 루프의 힘

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#의 2D 배열

4. C# 2D 배열에 요소 삽입

이제 C# 2D 배열에 요소를 삽입하는 방법에 대한 예를 살펴보겠습니다. 아이디어는 배열의 각 위치를 순회하여 값을 할당하는 것입니다.

코드

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#의 2D 배열

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#의 2D 배열

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#의 2D 배열

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#의 2D 배열의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:C#의 배열다음 기사:C#의 배열