stack是一种先进先出(First In Last Out, FILO)的数据结构。它只有一个出口。stack允许新增元素、移除元素、取得最顶端元素。它只有一个出口;stack允许新增元素、移除元素、取得最顶端元素。单除了最顶端外,没有任何其它方法可以存取stack的其它元素。换言之,stack不许与有遍历行为。
根据stack的性质,可知stack可用之前介绍的vector,list,deque做为底层的实现进行处理;
stack的定义如下
template<class T, class Sequence = deque<T>>
class stack {
friend bool operator == __STL_NULL_TMPL_ARGS(const stack&, const stack&);
friend bool operator < __STL_NULL_TMPL_ARGS(const stack&, const stack&);
public:
typedef typename Sequence::value_type value_type;
typedef typename Sequence::size_type size_type;
typedef typename Sequence::reference reference;
typedef typename Sequence::const_reference const_reference;
protected:
Sequence c;
public:
bool empty() const {return c.empty();}
size_type size() const {return c.size();}
reference top() {return c.back();}
const_reference top() const {return c.back();}
void push(const value_type&x) {c.push_back(x);}
void pop() {c.pop_back();}
};
template <class T, class Sequence>
bool operator == (const stack<T, Sequence>& x, const stack<T,Sequence>&y) {
return x.c == y.c;
}
template <class T, class Sequence>
bool operator < (const stack<T, Sequence>& x, const stack<T,Sequence>&y) {
return x.c < y.c;
}
从以上定义可知,只需要实现了empty(),size(),back(),push_back(),pop_back()及operator ==及<的容器都可作为stack的容器;
如需将stack的底层容器换成list;只需定义时增加Sequence参数即可
stack<int, list<int>> istack;
stack只能访问栈尾的元素;所以不能对数据进行遍历;所以没有对外可访问的迭代器;