rueki
3.1 C++ STL 스택 본문
728x90
반응형
C++에서는 STL을 통한 스택을 쉽게 사용할 수가 있다.
stack 안에 포함된 멤버 함수로는 아래와 같다.
- emplace
- empty
- pop
- push
- size
- swap
- top
- Size : 스택의 사이즈를 반환받는 함수
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> myints;
cout << "0. size : " << myints.size() << '\n';
for (int i = 0; i < 5; i++)
myints.push(i);
cout << "1. size : " << myints.size() << '\n';
myints.pop();
cout << "2. size : " << myints.size() << '\n';
return 0;
}
/*
0. size : 0
1. size : 5
2. size : 4
*/
- push & pop : 스택 내 원소 삽입 및 꺼내기
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> mystack;
for (int i = 0; i < 5; i++)
{
mystack.push(i);
}
cout << "Popping out elements";
while (!mystack.empty())
{
cout << ' ' << mystack.top();
mystack.pop();
}
cout << '\n';
return 0;
}
- swap : 원소 간의 교환
c++의 STL의 Algorithm에 Swap이 존재하고, Stack에 역시 존재한다.
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> mystack;
stack<int> mystack2;
mystack.push(20); mystack.push(40);
mystack2.push(30); mystack2.push(50);
mystack.swap(mystack2);
cout << mystack.top()<<' ';
mystack.pop();
cout << mystack.top()<<' ';
mystack.pop();
return 0;
}
mystack에는 20,40을 push, mystack2에는 30,50을 push하고 두 스택을 스왑한 코드이다.
-emplace : 스택 맨 위에 현재 맨 위 요소 위에 새 요소를 추가한다. 매개변수를 받아야함
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
std::stack<std::string> mystack;
mystack.emplace("First sentence");
mystack.emplace("Second sentence");
std::cout << "mystack contains:\n";
while (!mystack.empty())
{
std::cout << mystack.top() << '\n';
mystack.pop();
}
return 0;
}
/*
mystack contains:
Second sentence
First sentence
*/
728x90
반응형
'C,C++ 기초 및 자료구조' 카테고리의 다른 글
5. 버블 정렬 (Bubble Sort) (0) | 2020.03.21 |
---|---|
C++ STL 큐(QUEUE) (0) | 2020.03.12 |
4. 큐 (Queue) (0) | 2020.03.08 |
3. 스택 (0) | 2020.03.05 |
2.2 이진 검색 (Binary Search) (0) | 2020.03.04 |
Comments