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

C# Stack.Clear() 메서드 완벽 가이드 – 스택의 모든 요소 한 번에 제거하기

개요

C#의 Stack.Clear() 메서드는 스택(Stack)에 저장된 모든 개체를 한 번에 제거하는 데 사용됩니다. 이 메서드를 호출하면 스택의 Count 값이 0이 되어 빈 스택이 되지만, 내부적으로 할당된 용량(Capacity)은 그대로 유지된다는 점이 특징입니다.

구문

Stack.Clear() 메서드의 구문은 다음과 같습니다.

public virtual void Clear ();

이 메서드는 매개변수를 받지 않으며, 반환값도 없습니다(void). 단순히 스택 내부의 모든 요소를 삭제하는 역할만 수행합니다.

예제 1: 문자열 스택에서 Clear() 사용하기

다음 예제는 문자열 요소로 구성된 스택에 새 항목을 추가한 후, Clear() 메서드로 전체 요소를 제거하는 과정을 보여줍니다.

using System;
using System.Collections;
public class Demo {
   public static void Main() {
      Stack stack = new Stack();
      stack.Push("Inspiron");
      stack.Push("Alienware");
      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);
      stack.Push("Ultrabook");
      stack.Push("Cameras");
      stack.Push("Keyboards");
      Console.WriteLine("\nStack elements...updated");
      foreach(string val in stack) {
         Console.WriteLine(val);
      }
      Console.WriteLine("\nCount of elements (updated) = "+stack.Count);
      stack.Clear();
      Console.Write("Count of elements (updated) = "+stack.Count);
   }
}

실행 결과

위 코드를 실행하면 다음과 같은 출력 결과를 얻을 수 있습니다.

Stack elements...
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements = 7
Stack elements...updated
Keyboards
Cameras
Ultrabook
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements (updated) = 10
Count of elements (updated) = 0

출력 결과에서 확인할 수 있듯이, 처음 7개의 요소에 3개를 추가해 총 10개가 되었고, Clear() 호출 직후 Count가 0으로 변경되었습니다.

예제 2: 정수 스택에서 Clear() 사용하기

이번에는 정수(int) 타입의 요소를 저장한 스택에 대해 동일하게 Clear() 메서드를 적용해 보겠습니다.

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);
      stack.Push(3000);
      stack.Push(3500);
      stack.Push(4000);
      Console.WriteLine("\nStack elements...updated");
      foreach(int val in stack) {
         Console.WriteLine(val);
      }
      Console.WriteLine("\nCount of elements (updated) = "+stack.Count);
      stack.Clear();
      Console.Write("Count of elements (updated) = "+stack.Count);
   }
}

실행 결과

위 코드를 실행하면 다음과 같은 출력 결과를 얻을 수 있습니다.

Stack elements...
2500
2000
1500
1250
1000
750
500
300
150
Count of elements = 9
Stack elements...updated
4000
3500
3000
2500
2000
1500
1250
1000
750
500
300
150
Count of elements (updated) = 12
Count of elements (updated) = 0

정리

Stack.Clear() 메서드는 스택을 초기화할 때 유용하게 활용됩니다. 핵심 특징을 정리하면 다음과 같습니다.

- 스택에 저장된 모든 요소를 한 번에 제거합니다.
- 호출 후 Count 속성이 0이 됩니다.
- 매개변수와 반환값이 없는 간단한 구조입니다.
- 내부 배열의 용량은 유지되므로, 이후 다시 Push를 하면 재할당 비용을 줄일 수 있습니다.

스택을 재사용하면서 기존 데이터를 모두 지우고 싶을 때, 요소를 하나씩 Pop() 하는 대신 Clear() 메서드를 사용하면 훨씬 간결하고 효율적인 코드를 작성할 수 있습니다.