1.stack
stack是一种先进后出的数据结构,它只有一个出口。stack允许新增元素、移除元素、取得最顶元素。但除了最顶端外,没有任何其他方法可以存取stack的其他元素。换言之,stack不允许有遍历行为。
以某种既有容器作为底层结构,将其接口改变,使之符合“先进后出”的特性,形成一个stack,是很容易做到的。deque
是双向开口的数据结构,若以deque为底部结构并封闭其头端开口,便轻而易举地形成一个stack。因此,SGI STL便以deque作为缺省情况下的stack底部结构。
由于stack系以底部容器完成其所有工作,而具有这种“修改某物接口,形成另一种风貌”之性质者,称为adapter,因此,STL stack往往不被归类为container(容器),而被归类为container 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:
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;
}
stack所有元素的进出都必须符合“先进后出”的条件,只有stack顶端的元素,才有机会被外界取用。stack不提供走访功能,也不提供迭代器。
2.函数成员
/// The default constructor. Creates an empty stack.
stack();
/// The copy constructor.
stack(const stack&);
/// The assignment operator.
stack& operator=(const stack&);
/// Returns true if the stack contains no elements, and false otherwise.
bool empty() const;
/// Returns the number of elements contained in the stack.
size_type size() const;
/// Returns a mutable reference to the element at the top of the stack.
value_type& top();
/// Returns a const reference to the element at the top of the stack.
const value_type& top() const;
/// Inserts x at the top of the stack
void push(const value_type&);
/// Removes the element at the top of the stack.
void pop();
/// Compares two stacks for equality.
bool operator==(const stack&, const stack&);
/// Lexicographical ordering of two stacks.
bool operator<(const stack&, const stack&);
3.参考文献
本文内容摘录于《STL源码剖析》