std::stack
类是容器适配器,它给予程序员栈的功能——特别是 FILO (先进后出)数据结构。
该类模板表现为底层容器的包装器——只提供特定函数集合。栈从被称作栈顶的容器尾部推弹元素。
元素访问
top:访问栈顶元素
容量
empty:检查底层的容器是否为空
size:返回容纳的元素数
修改器
push:向栈顶插入元素
emplace:于顶原位构造元素
pop:删除栈顶的元素
swap:交换内容
#include <bits/stdc++.h>
using namespace std;
int main(){
stack<int> stack1; // (尾)5 2 0(首)
stack1.push(5);//向栈顶插入元素
stack1.push(2);
stack1.push(0);
cout<<stack1.top()<<endl;//访问栈顶元素
cout<<stack1.empty()<<endl;//检查底层的容器是否为空
cout<<stack1.size()<<endl;//返回容纳的元素数
stack1.pop();//删除栈顶元素
cout<<stack1.top()<<endl;
stack<int> stack2;
stack2.push(30);
stack2.push(32);
stack1.swap(stack2);
cout<<stack1.top()<<endl;
stack1.pop();
cout<<stack1.top()<<endl;
return 0;
}