第 18.6 節

stack 容器

0瀏覽次數0訪問次數--跳出率--平均停留

Stack container

stack 基本概念

Concept: A stack is a First In Last Out (FILO) data structure that only has one exit point.

Description: 11-15-2015_195707

Only the top element of the stack is accessible from the outside, so traversal is not permitted.

Data entering the stack is called --- stack push push

Popping data from a stack is called --- popping pop

Stacks in daily life:

img

img

Common interfaces of a stack.

Function Description: Common public interfaces for stack container

Constructor:

  • stack<T> stk; //stack is implemented using a template class; the default construction form of stack objects
  • stack(const stack &stk); //copy constructor

Assignment operation:

  • stack& operator=(const stack &stk); //overloading the equality operator

Data Access:

  • push(elem); //Add an element to the top of the stack
  • pop(); //Remove the first element from the top of the stack
  • top(); //return the top element of the stack

Size Operations:

  • empty(); //Check if the stack is empty
  • size(); //return stack size

Example:

#include <iostream>
#include <stack>

using namespace std;

//栈容器常用接口
void test01()
{
    //创建栈容器 栈容器必须符合先进后出
    stack<int> s;

    //向栈中添加元素,叫做 压栈 入栈
    s.push(10);
    s.push(20);
    s.push(30);

    while (!s.empty()) {
        //输出栈顶元素
        cout << "栈顶元素为: " << s.top() << endl;
        //弹出栈顶元素
        s.pop();
    }
    cout << "栈的大小为:" << s.size() << endl;

}

int main() {

    test01();


    return 0;
}

运行结果:

栈顶元素为: 30
栈顶元素为: 20
栈顶元素为: 10
栈的大小为:0

Summary:

  • Push ---入栈
  • Pop --- 出栈
  • return top of stack --- top
  • Check if the stack is empty --- empty
  • Return stack size
音乐页