Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# Stack.CopyTo() 메서드 완벽 정리 – 문법, 동작 원리, 실전 예제

C# Stack.CopyTo() 메서드란?

C#의 Stack.CopyTo() 메서드는 스택(Stack)에 담긴 요소들을 이미 존재하는 1차원 배열(Array)로 복사하는 기능을 제공합니다. 이때 복사 작업은 사용자가 지정한 배열 인덱스 위치부터 시작되며, 복사되는 순서는 스택의 LIFO(후입선출) 구조를 그대로 따릅니다. 즉, 가장 마지막에 Push된 요소부터 배열 앞쪽에 차례대로 저장됩니다.

문법(Syntax)

CopyTo() 메서드의 기본 문법은 다음과 같습니다.

public virtual void CopyTo (Array arr, int index);

각 매개변수의 역할은 아래와 같습니다.

  • arr: 스택에서 복사한 요소들이 저장될 대상 1차원 배열입니다.
  • index: 복사가 시작되는 배열의 인덱스 위치입니다.

메서드 호출 시 전달하는 배열이 null이거나 인덱스가 음수일 경우, 또는 배열의 크기가 부족하면 ArgumentNullException, ArgumentOutOfRangeException, ArgumentException 등의 예외가 발생할 수 있으므로 배열 크기를 충분히 확보해 두는 것이 좋습니다.

예제 1: 정수형 스택을 배열로 복사하기

다음 예제에서는 정수 요소를 가진 스택을 생성한 뒤, Clone() 메서드로 복제하고 CopyTo()를 사용하여 정수 배열로 복사하는 과정을 살펴봅니다.

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      Stack stack = new Stack();
      stack.Push(150);
      stack.Push(300);
      stack.Push(500);
      stack.Push(750);
      stack.Push(1000);
      stack.Push(1250);
      stack.Push(1500);
      stack.Push(2000);
      stack.Push(2500);
      Console.WriteLine("Stack elements...");
      foreach(int val in stack){
         Console.WriteLine(val);
      }
      Console.WriteLine("Count of elements = "+stack.Count);
      Console.WriteLine("Element 750 is the stack? = "+stack.Contains(750));
      stack.Push(3000);
      Console.WriteLine("\nStack elements...updated");
      foreach(int val in stack)
      {
         Console.WriteLine(val);
      }
      Console.WriteLine("Count of elements (updated) = "+stack.Count);
      Console.WriteLine("Element 5000 is the stack? = "+stack.Contains(5000));
      Stack stack2 = (Stack)stack.Clone();
      Console.WriteLine("\nStack elements...cloned");
      foreach(int val in stack2){
         Console.WriteLine(val);
      }
      Console.WriteLine("Count of elements (updated) = "+stack2.Count);
      Console.WriteLine("\nCopying the cloned stack to an integer array...");
      int[] intArr = new int[stack2.Count];
      stack2.CopyTo(intArr, 0);
      foreach(int j in intArr){
         Console.WriteLine(j);
      }
   }
}

실행 결과

위 프로그램을 실행하면 다음과 같은 출력이 표시됩니다.

Stack elements...
2500
2000
1500
1250
1000
750
500
300
150
Count of elements = 9
Element 750 is the stack? = True
Stack elements...updated
3000
2500
2000
1500
1250
1000
750
500
300
150
Count of elements (updated) = 10
Element 5000 is the stack? = False
Stack elements...cloned
3000
2500
2000
1500
1250
1000
750
500
300
150
Count of elements (updated) = 10
Copying the cloned stack to an integer array...
3000
2500
2000
1500
1250
1000
750
500
300
150

출력 결과를 보면 스택의 최상단 요소인 3000부터 배열의 인덱스 0번째 자리에 순서대로 복사된 것을 확인할 수 있습니다. 이것이 바로 CopyTo()가 LIFO 구조를 유지하며 복사한다는 점을 보여주는 부분입니다.

예제 2: 문자열 스택을 배열로 복사하기

이번에는 문자열 타입의 요소를 가진 스택을 문자열 배열로 복사하는 예제입니다.

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      Stack stack = new Stack();
      stack.Push("Projectors");
      stack.Push("Monitors");
      stack.Push("XPS");
      stack.Push("Laptop");
      stack.Push("Notebook");
      Console.WriteLine("Stack elements...");
      foreach(string val in stack){
         Console.WriteLine(val);
      }
      Console.WriteLine("Count of elements = "+stack.Count);
      Console.WriteLine("Element XPS is the stack? = "+stack.Contains("XPS"));
      stack.Push("Ultrabook");
      Console.WriteLine("\nStack elements...updated");
      foreach(string val in stack){
         Console.WriteLine(val);
      }
      Console.WriteLine("Count of elements (updated) = "+stack.Count);
      Console.WriteLine("Element Ultrabook is the stack? = "+stack.Contains("Ultrabook"));
      Stack stack2 = (Stack)stack.Clone();
      Console.WriteLine("\nStack elements...cloned");
      foreach(string val in stack2){
         Console.WriteLine(val);
      }
      Console.WriteLine("Count of elements (updated) = "+stack2.Count);
      Console.WriteLine("\nCopying the cloned stack to a string array...");
      string[] strArr = new string[stack2.Count];
      stack2.CopyTo(strArr, 0);
      foreach(string j in strArr){
         Console.WriteLine(j);
      }
   }
}

실행 결과

프로그램을 실행하면 아래와 같은 결과가 출력됩니다.

Stack elements...
Notebook
Laptop
XPS
Monitors
Projectors
Count of elements = 5
Element XPS is the stack? = True
Stack elements...updated
Ultrabook
Notebook
Laptop
XPS
Monitors
Projectors
Count of elements (updated) = 6
Element Ultrabook is the stack? = True
Stack elements...cloned
Ultrabook
Notebook
Laptop
XPS
Monitors
Projectors
Count of elements (updated) = 6
Copying the cloned stack to a string array...
Ultrabook
Notebook
Laptop
XPS
Monitors
Projectors

정리

Stack.CopyTo() 메서드는 스택의 내용을 배열 형태로 변환해야 할 때 유용하게 활용됩니다. 핵심 포인트를 요약하면 다음과 같습니다.

  • 복사 대상은 반드시 1차원 배열이어야 하며, 배열 크기는 스택의 Count 이상이어야 합니다.
  • 복사는 지정한 인덱스부터 시작되므로, 필요에 따라 특정 위치에만 삽입하는 것도 가능합니다.
  • 복사 순서는 스택의 후입선출(LIFO) 구조를 그대로 따르므로, 마지막에 추가된 요소가 배열의 앞쪽에 위치합니다.