1. 개요

std::stack은 후입선출(LIFO, Last-In-First-Out) 방식의 컨테이너 어댑터입니다. <stack> 헤더에 정의되어 있으며, 기본적으로 std::deque를 기반으로 동작하지만, std::vector나 다른 컨테이너도 사용 가능하게 설계되어 있습니다.

 #include <stack>
 std::stack<int> s;

2. 주요 특징

  • LIFO 구조
  • 맨 위(top) 요소에만 접근 가능
  • 삽입/삭제는 push() / pop()을 통해 수행
  • 반복자 사용 불가 (직접 순회 불가)
  • 내부 컨테이너는 기본적으로 deque 사용

    3. 주요 멤버 함수

함수 설명
empty() 비었는지 확인
size() 요소 수 반환
top() 맨 위 요소 반환
push(val) 요소 추가
pop() 맨 위 요소 제거
emplace(args...) 요소 직접 생성 후 추가
swap(other) 다른 스택과 교환

4. 예제 코드

 #include <iostream>
 #include <stack>
 using namespace std;
 
 int main() {
     stack<int> s;
     s.push(10);
     s.push(20);
     s.push(30);
 
     cout << "Top: " << s.top() << endl;  // 30
 
     s.pop();
     cout << "After pop, Top: " << s.top() << endl;  // 20
 
     while (!s.empty()) {
         cout << "Popped: " << s.top() << endl;
         s.pop();
     }
 
     return 0;
 }

5. 내부 컨테이너 지정

 #include <stack>
 #include <vector>
 
 std::stack<int, std::vector<int>> s2;
  • std::deque, std::vector, std::list 등 시퀀스 컨테이너를 기반으로 가능
  • 단, back(), push_back(), pop_back() 멤버가 존재해야 함

    6. std::queue*와의 비교

항목 std::stack std::queue
구조 LIFO FIFO
삽입 위치
제거 위치
접근 가능 top() front(), back()

7. 주의사항

  • 반복자(iterator)를 제공하지 않음
  • 스택 내부를 탐색하고 싶다면 기반 컨테이너 사용 권장 (std::deque 등)
  • 디버깅 시 while (!s.empty()) 형태로 요소 접근

글 이동

Comments