queue單向隊列

queue單向隊列與有點類似,一個是在同一端存取數據,另一個是在一端存入數據,另一端取出數據。單向隊列中的數據是先進先出(First In First Out,FIFO)。在STL中,單向隊列也是以別的容器作爲底部結構,再將接口改變,使之符合單向隊列的特性就可以了。因此實現也是非常方便的。下面就給出單向隊列的函數列表和VS2008中單向隊列的源代碼。單向隊列一共6個常用函數(front()、back()、push()、pop()、empty()、size()),與的常用函數較爲相似。

<span style="font-size:18px;">//VS2008中 queue的定義 MoreWindows整理(http://blog.csdn.net/MoreWindows)
template<class _Ty, class _Container = deque<_Ty> >
class queue
{ // FIFO queue implemented with a container
public:
typedef _Container container_type;
typedef typename _Container::value_type value_type;
typedef typename _Container::size_type size_type;
typedef typename _Container::reference reference;
typedef typename _Container::const_reference const_reference;


queue() : c()
{ // construct with empty container
}


explicit queue(const _Container& _Cont) : c(_Cont)
{ // construct by copying specified container
}


bool empty() const
{ // test if queue is empty
return (c.empty());
}


size_type size() const
{ // return length of queue
return (c.size());
}


reference front()
{ // return first element of mutable queue
return (c.front());
}


const_reference front() const
{ // return first element of nonmutable queue
return (c.front());
}


reference back()
{ // return last element of mutable queue
return (c.back());
}


const_reference back() const
{ // return last element of nonmutable queue
return (c.back());
}


void push(const value_type& _Val)
{ // insert element at beginning
c.push_back(_Val);
}


void pop()
{ // erase element at end
c.pop_front();
}


const _Container& _Get_container() const
{ // get reference to container
return (c);
}


protected:
_Container c; // the underlying container
};</span>


可以看出,由於queue只是進一步封裝別的數據結構,並提供自己的接口,所以代碼非常簡潔,如果不指定容器,默認是用deque來作爲其底層數據結構的(對deque不是很瞭解?可以參閱《STL系列之一deque雙向隊列》)。下面給出單向隊列的使用範例:

//單向隊列 queue支持 empty() size() front() back() push() pop()
//By MoreWindows(http://blog.csdn.net/MoreWindows)
#include <queue>
#include <vector>
#include <list>
#include <cstdio>
using namespace std;


int main()
{
//可以使用list作爲單向隊列的容器,默認是使用deque的。
queue<int, list<int>> a;
queue<int>        b;
int i;


//壓入數據
for (i = 0; i < 10; i++)
{
a.push(i);
b.push(i);
}


//單向隊列的大小
printf("%d %d\n", a.size(), b.size());


//隊列頭和隊列尾
printf("%d %d\n", a.front(), a.back());
printf("%d %d\n", b.front(), b.back());


//取單向隊列項數據並將數據移出單向隊列
while (!a.empty())
{
printf("%d ", a.front());
a.pop();
}
putchar('\n');


while (!b.empty())
{
printf("%d ", b.front());
b.pop();
}
putchar('\n');
return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章