1、概述
stack是一种先进后出(First In Last Out, FIFO)的数据结构。它只有一个出口,stack允许新增元素、移除元素、取得最顶端元素。stack不允许有遍历行为。
由于stack系以底部容器完成其所有工作,而具有这种“修改某物借口,形成另一种风貌”之性职者,称为adapter(配接器)。因此STL stack往往不被归类为container(容器),而被归类为container adapter(容器适配器)。
使用时需要包含头文件 #include<stack>。
stack的声明如下:
namespace std
{
template <class T, class Sequence = daque<T> >
class stack;
}
第一个模板参数表示元素的类型,第二个模板参数表示实现栈所使用的容器。STL 以deque作为缺省情况下的stack底部结构。
定义一个stack:
std::stack <int> st;
2、成员函数
(1)empty 判断栈是否为空。如果栈为空,返回true,否则返回false。
bool empty() const {return c.empty();};
st.empty();
扫描二维码关注公众号,回复:
2225383 查看本文章
(2)size 返回栈的大小
size_type size() const {return c.size()};
st.size();
(3)top 返回栈顶元素,并不会移除这个元素(注意,返回的是栈顶元素的引)。
value_type& top()
(4)push 插入元素到栈顶
void push(const value_type& x){c.push_back(x);}
st.push(6);
(5)pop 移除栈顶元素
void pop() {c.pop_back;}
nt n = st.top();st.pop();
3、类型
(1)std::stack::value_type 元素的类型
(2)std::stack::size_type 无符号的整数类型,用于定义 stack 的大小
(3)std::stack::container_type 容器类型