浅谈C++ STL stack 容器
本篇随笔简单介绍一下(C++STL)中(stack)容器的使用方法和常见的使用技巧。
stack容器的概念
(stack)在英文中是栈的意思。栈是一种基本的数据结构。而(C++STL)中的栈就是把这种数据结构模板化了。
栈的示意图如下:这是一个先进后出的数据结构。这非常重要!!
事实上,(stack)容器并不是一种标准的数据结构,它其实是一个容器适配器,里面还可以存其他的(STL)容器。但那种使用方法过于高深而且不是很常用,所以在此不与介绍。请有兴趣的读者自行查询资料。
stack容器的声明
(stack)容器存放在模板库:#include<stack>
里,使用前需要先开这个库。
(stack)容器的声明遵循(C++STL)的一般声明原则:
容器类型<变量类型> 名称
例:
#include<stack>
stack<int> st;
stack<char> st;
stack<pair<int,int> > st;
stack<node> st;
struct node{...};
stack容器的使用方法
(stack)容器的使用方法大致如下表所示:
用法 | 作用 |
---|---|
st.top() |
返回stack的栈顶元素 |
st.push() |
从stack栈顶加入一个元素 |
st.size() |
返回stack当前的长度(大小) |
st.pop() |
从stack栈顶弹出一个元素 |
st.empty() |
返回stack是否为空,1为空、0不为空 |