一、概述
stack是一种先进后出(FILO)的数据结构,它只有一个出口。stack允许新增元素、移除元素、取得栈顶元素,除了栈顶元素,取不到其他元素,即栈不允许遍历,也不提供迭代器。deque作为stack的底层容器,可以轻易的形成一个stack。因此,SGI STL以deque作为缺省情况下的stack的底部结构。所以stack也是容器配接器。使用stack之前须先含入头文件<stack>。
二、stack的核心接口
在头文件<stack>中,class stack定义如下:
namespace std {
template <class T,
class Container = deque<T> >
class stack;
}
第一个参数代表元素类型,带有默认值的第二个参数定义stack内部存放元素所使用的容器,缺省使用deque。之所以使用deque而非vector,是因为deque移除元素释放内存,并且不必在重新分配时复制所有元素。也可以使用vector或者list来容纳元素:
std::stack<int, std::vector<int> > st;
- size()返回stack的数据元素个数。
- empty()判断stack是否为空,空返回true。
- push()会将一个元素置入stack中。
- top()会返回stack内的下一个元素,即栈顶元素。
- pop()会删除stack中下一个元素,即栈顶元素
三、程序示例
stack的使用示例
//example of stack,use deque to construct stack
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> st;
st.push(1);
st.push(2);
st.push(3);
// pop and print two elements from the stack
cout << st.top() << ' ';
st.pop();
cout << st.top() << ' ';
st.pop();
st.top() = 77;
st.push(4);
st.push(5);
st.pop();
while (!st.empty()) {
cout << st.top() << ' ';
st.pop();
}
cout << endl;
return 0;
}
输出结果:
以list作为stack的底层容器实例:
#include<stack>
#include<list>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
stack<int, list<int> > istack;
istack.push(1);
istack.push(3);
istack.push(5);
istack.push(7);
cout << istack.size() << endl;
cout << istack.top() << endl;
istack.pop(); cout << istack.top() << endl;
istack.pop(); cout << istack.top() << endl;
istack.pop(); cout << istack.top() << endl;
cout << istack.size() << endl;
return 0;
}
输出结果: