1. 程式人生 > >c++ stl queue(FIFO,容器配接器)

c++ stl queue(FIFO,容器配接器)

1.queue

  queue是一種先進先出的資料結構,它有兩個出口。queue允許新增元素、移除元素、從最底端加入元素、取得最頂端元素。但除了最底端可以加入、最頂端可以取出外,沒有任何其他方法可以存取queue的其它元素。換言之,queue不允許有遍歷行為。
  將元素推入queue的操作稱為push,將元素推出queue的操作稱為pop。



  以某種既有容器為底部結構,將其介面改變,使其符合“先進先出”的特性,形成一個queue,是很容易做到的。deque是雙向開口的資料結構,若以deque為底部結構並封閉其底端的出口和前端的入口,便輕而易舉地形成一個queue。因此,SGI STL便以deque作為預設情況下的queue底部結構。
  由於queue系以底部容器完成其所有工作,而具有這種“修改某物介面,形成另一種風貌”之性質者,稱為adapter,因此,STL stack往往不被歸類為container(容器),而被歸類為container adapter。
template <class T,class Sequence = deque<T> >
class queue
{
    friend bool operator == __STL_NULL_TMPL_ARGS (const queue& x,const queue& y);
    friend bool operator < __STL_NULL_TMPL_ARGS (const queue& x,const queue& y);
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 front() { return c.front(); }
    const_reference front() const { return c.front(); }
    reference back() { return c.back(); }
    const_reference back() 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 queue<T,Sequence>& x,const queue<T,Sequence>& y)
{
    return x.c == y.c;
}
template <class T,class Sequence>
bool operator < (const queue<T,Sequence>& x,const queue<T,Sequence>& y)
{
    return x.c < y.c;
}
  queue所有元素的進出都必須符合“先進先出”的條件,只有queue頂端的元素,才有機會被外界取用。queue不提供遍歷功能,也不提供迭代器。

2.函式成員

/// The default constructor. Creates an empty queue.
queue();
/// The copy constructor.
queue(const queue&);
/// The assignment operator.
queue& operator=(const queue&);
/// Returns true if the queue contains no elements, and false otherwise.
bool empty() const;
/// Returns the number of elements contained in the queue.
size_type size() const;
/// Returns a mutable reference to the element at the front of the queue, that is, the element least recently inserted.
value_type& front();
/// Returns a const reference to the element at the front of the queue, that is, the element least recently inserted.
const value_type& front() const;
/// Returns a mutable reference to the element at the back of the queue, that is, the element most recently inserted.
value_type& back();
/// Returns a const reference to the element at the back of the queue, that is, the element most recently inserted.
const value_type& back() const;
/// Inserts x at the back of the queue.
void push(const value_type& x);
/// Removes the element at the front of the queue.
void pop();
/// Compares two queues for equality.
bool operator==(const queue&, const queue&);
/// Lexicographical ordering of two queues.
bool operator<(const queue&, const queue&);

3.參考文獻

  本文內容摘錄於《STL原始碼剖析》