C++学习 --- STL常用容器之stack容器

4、stack 容器

4.1、stack基本概念

概念:stack是一种先进后出(First In Last out,FILO)的数据结构,它只有一个出口。

 

栈中只有顶端的元素才可以被外界使用,因此栈不允许有遍历行为。

栈中进入数据称为 --- 入栈 push

栈中弹出数据称为 --- 出栈 pop

4.2、stack常用接口

 

#include <iostream>
#include <stack>
using namespace std;
​
//stack栈容器
void test01() {
    //栈的特点:符合先进后出数据结构
    stack<int> s;
    
    //入栈
    s.push(10);
    s.push(20);
    s.push(30);
    s.push(40);
​
    cout << "栈的大小:" << s.size() << endl;
    //只要栈不为空,查看栈顶,并执行出栈操作
    while (!s.empty()) {
        //查看栈顶的元素
        cout << "栈顶元素为:" << s.top() << endl;
​
        //出栈
        s.pop();
    }
    cout << "栈的大小:" << s.size() << endl;
}
​
int main() {
    test01();
​
    system("pause");
    return 0;
}

 

 

posted @ 2021-10-11 10:00  yiwenzhang  阅读(81)  评论(0编辑  收藏  举报