stack:是一种先进后出的数据结构,只有一个出口。允许新增元素、移除元素、取得最顶端元素,但除了最顶端外,没有任何其它方法可以存取stack的其他元素,即stack不允许由遍历行为。
stack以底部容器deque完成其所有工作,成为adapter(配接器)。
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:
//以下利用Sequence c的操作,完成stack的操作
bool empty()const { return c.empty(); }
size_type size()const { return c.size(); }
reference top()const { return c.back(); }
const_reference top()const { return c.back(); }
//deque是两头可进出,stack是末端进出
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;
}
迭代器
stack没有迭代器
以list作为底层容器的stack
list也是双向开口的数据结构,若以list为底部结构并封闭其头端开口,一样能够轻易形成一个stack。