프로그래밍/C++

[C/C++] C++ STL Stack 기본 사용법 및 예제

준코딩 2019. 8. 22. 16:05

사용 라이브러리

 

      · <stack>

 

 

기본함수

 

      선언문

 

         · stack < 자료형 > s;

 

 

     삽입 및 추출

 

         · push(element) : 가장 위에 원소를 삽입

         · pop() : 가장 위에 있는 원소 추출

 

 

      조회

     

         · top() : 가장 위에 있는 원소를 가져옴

 

 

      기타 함수

     

         · empty() : 비어있는 경우 1을 , 그렇지 않은 경우 0을 반환

         · size() : 원소의 수를 반환

 

 

예제 코드

#include <iostream>
#include <stack>

using namespace std;

int main() {

	stack<int> s;

	////////////삽입 및 추출/////////////////
	s.push(1);  // 1
	s.push(2);  // 2 1
	s.push(3);  // 3 2 1
	s.push(4);  // 4 3 2 1
	s.pop();    // 3 2 1
	s.pop();    // 2 1
	s.push(3);  // 3 2 1

	/////////////////조회////////////////////
	int test = s.top(); // test = 3
	cout << test;       // 3
	cout << s.top();    // 3

	///////////////기타 함수///////////////
	cout << s.empty();  // false
	cout << s.size();   // 3 <- 3개의 원소

	////////////////초기화////////////////
	s = stack<int>();  // 원래 스택에 빈 스택을 넣는다.
	cout << s.empty(); // true

	return 0;
}