• stack是STL中的一种后进先出容器
  • 可以自己实现一个栈:​​数据结构(4)栈和队列->栈​​
  • STL中的stack支持任意基本数量类型和STL容器
  • stack定义于​​stack.h​​​,命名空间​​std​

一、构造函数

作用

代码

说明

定义一个stack

stack<typename> st;

typename可以是任意基础数据类型或STL容器

二、访问stack内元素

  • 由于队列本身是一个先进先出的限制性结构,因此STL中只能访问栈顶元素​​stack.top()​
#include <iostream>
#include <stack>
using namespace std;

int main()
{
stack<int> st;
for(int i=1;i<=5;i++)
st.push(i);

cout<<st.top()<<endl; //打印5

return 0;
}

三、常用操作

  • 设有stack容器st

操作

代码

时间复杂度

说明

元素x入队

st.push(x)

O(1)

-

弹出栈顶元素

st.pop()

O(1)

-

栈判空

st.empty()

O(1)

返回一个bool类型

访问栈顶元素(不影响栈)

st.top()

O(1)

如果队列为空,top()方法会报错

获得queue内元素个数

q.size()

O(1)

-

#include <iostream>
#include <stack>
using namespace std;

int main()
{
stack<int> st;
for(int i=1;i<=5;i++) //push()方法
st.push(i);

cout<<st.top()<<endl; //top()方法

st.pop(); //pop()方法
cout<<st.top()<<endl; //top()方法

cout<<st.size()<<endl; //empty()方法
cout<<"栈空吗:"<<st.empty()<<endl;

for(int i=1;i<=4;i++)
st.pop();

cout<<"栈空吗:"<<st.empty();

return 0;
}

/*
5
4
4
栈空吗:0
栈空吗:1
*/