#include<stack>栈的基本操作

2023年7月13日11:09:32

介绍

  1. stack的定义
    其定义的写法和其他STL容器相同, typename可以任意基本数据类型或容器:
    stack name;
  2. stack容器内元素的访问
    由于栈(stack)本身就是一种后进先出的数据结构,在STL的 stack中只能通过top()来访问栈顶元素。

这里我就用int类型的名叫tx的栈

stack<int>tx;

相关函数及其用法

一.
empty():判断栈是否为空的函数,栈空返回true,反之返回false
push(x):x入栈函数
size():返回栈内元素个数的函数
pop():栈顶出栈函数
top():返回栈顶元素函数


#include<cstdio>
#include<iostream>
#include<stack>
using namespace std;
int main(){
    stack<int>tx;
    cout<<"tx栈的空满性判断:"<<tx.empty()<<endl;//为空返回true,非空返回false
    for(int i=1;i<5;i++){
        tx.push(i);//元素入栈
    }
    cout<<"tx栈的空满性判断:"<<tx.empty()<<endl;
    cout<<"栈元素个数是:"<<tx.size()<<endl;//栈元素个数
    for(int i=1;i<3;i++){
        tx.pop();//栈顶元素元素出栈
    }
    cout<<"栈顶元素:"<<tx.top()<<endl;//得到栈顶元素并打印
    return 0;
}


运行结果

tx栈的空满性判断:1
tx栈的空满性判断:0
栈元素个数是:4
栈顶元素:2
Program ended with exit code: 0

  • 作者:不正经的天线
  • 原文链接:https://blog.csdn.net/weixin_52793414/article/details/117406093
    更新时间:2023年7月13日11:09:32 ,共 678 字。