관리 메뉴

Kim's Programming

STL(Standard Template Library) - Container - Stack 본문

STL - Container

STL(Standard Template Library) - Container - Stack

Programmer. 2016. 1. 27. 20:04

자료구로 Stack은 선입후출(LIFO : Last In First Out)의 구조를 가진 자료구조입니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<iostream>
#include<stack>
 
void print(std::stack<int> Target_Stack)
{
    std::cout << "(top->)";
    while (!Target_Stack.empty())
    {
        std::cout << Target_Stack.top() << " ";
        Target_Stack.pop();
    }
    std::cout <<"(<-bottom)" <<std::endl;
}
 
 
void main()
{
    //Stack doesn't have iterator
    std::stack<int> Stack;
    std::stack<int> Stack_copy;
    //if Stack is empty, empty() function return true
    if (Stack.empty())
        std::cout << "Empty!" << std::endl;
 
    //push(x) function write 'x' to top of the Stack (LIFO)
    Stack.push(3);
    print(Stack);
    Stack.push(5);
    print(Stack);
    Stack.push(10);
    print(Stack);
 
    //pop()function remove data frop top (LIFO)
    std::cout << "POP()" << std::endl;
    std::cout << "Previous ->  "; print(Stack);
    Stack.pop();
    std::cout << "After ->  "; print(Stack);
 
    //operator '=' copy x1 to x2, previous data will be deleted
    std::cout << "operator =" << std::endl;
    std::cout << "Previous ->  "; print(Stack_copy);
    Stack_copy = Stack;
    std::cout << "After ->  "; print(Stack_copy);
 
    //size() function display this Stack's height
    std::cout << "size of Stack -> " << Stack.size() << std::endl;
 
    //emplace(x) function write 'x' to top of the Stack (LIFO)
    Stack.emplace(12);
    print(Stack);
 
    //top() function return data from Stack's top
    std::cout << Stack.top() << std::endl;
 
    //x1.swap(x2) function swap x1 and x2
    std::cout << "Previous  Stack ->  "; print(Stack);
    std::cout << "Previous  Stack_Copty ->  "; print(Stack_copy);
    Stack.swap(Stack_copy);
    std::cout << "After  Stack ->  "; print(Stack);
    std::cout << "After  Stack_Copty ->  "; print(Stack_copy);
 
 
}
cs


각 함수들의 기능을 알아보겠습니다.(함수이름을 클릭하면 상세 설명으로 이동합니다)

    1. empty()

      empty()함수는 스택이 비었을 때 True를 리턴하고 비어있지 않으면 false를 디턴합니다.

    2. push(x)

      스택 제일 위에 x를 밀어넣습니다.

    3. pop()

      스택 제일 위에 있는 데이터를 제거합니다.

    4. operator =

      a=b인 경우 스택 b의 내용을 스택 a에 그대로 복사하고 기존 a의 데이터는 삭제합니다.

    5. size()

      스택의 높이를 리턴합니다.

    6. emplace(x)

      'x' 데이터를 스택 제일 위에 삽입합니다.

    7. top()

      스택 제일 위에 있는 데이터를 리턴합니다.

    8. a.swap(b)

      스택 a와 스택 b의 내용을 완전히 바꿉니다.