1. 程式人生 > >C++基於模版的迴圈佇列實現

C++基於模版的迴圈佇列實現

近期因為要反反覆覆使用佇列,而佇列需要儲存的元素格式又千差萬別,在網上搜了下貌似雙邊佇列可以解決這個問題,但是效率有點低。於是自己寫了個基於模版的迴圈佇列實現方式,有任何不合理之處還請各位大牛輕怕。

#pragma once


template<class T>  // Template declaration
class CQueue
{
public:
CQueue(void);
CQueue(int num);
~CQueue(void);


private:
unsigned int rear,front,maxsize,currentcout;
T* elements;


public:


int Add(T element);
T* FetchElement();// get current element and delete it form the queue
T* ProbeElement();// get current element and retain it form the queue
int  Delete();
int IsEmpty();
int IsFull();
void InitElements();
int InitElements(int num);
void Destroy();


};




template<class T>
CQueue<T>::CQueue(void)
{


}


template<class T>
CQueue<T>::~CQueue(void)
{
if (elements)
{
delete []elements;
}
}


template<class T>
CQueue<T>::CQueue(int num)
{
elements = new T[num];
rear=front=0;
maxsize = num;
currentcout = 0;
}






template<class T> 
int CQueue<T> ::Add(T element)
{


if(currentcout!=maxsize)//((rear+1)%N!=front)
{
elements[rear]=element;
rear=(rear+1)%maxsize;
currentcout++;
}
else
return -1;


return 0;


}


template<class T>
int CQueue<T>::Delete()
{
if(currentcout == 0)
return -1;
else
{
front=(front+1)%N;
currentcout--;
}


return 0;
}


template<class T>
T* CQueue<T>::FetchElement()
{
T*temp = NULL;
if(currentcout==0)
{
return NULL;
}
else
{
temp = &elements[front];
front=(front+1)%maxsize;
currentcout--;
}


return temp;
}


template<class T>
T* CQueue<T>::ProbeElement()
{
if(currentcout==0)
return NULL;
else
return &elements[front];
}


template<class T>
int CQueue<T>::IsEmpty()
{
return currentcout == 0; 
}


template<class T>
int CQueue<T>::IsFull()
{
return currentcout == maxsize; 
}




/*
-using for init elements when you do not want to destroy CQeue object 
but want to give up elements already stored


*/
template<class T>
void CQueue<T>::InitElements()
{
rear = front = 0;
currentcout = 0;
}


/*
-using for init elements when you want to destroy current memory used for store elements 
and allocate a new memory area with length num


*/
template<class T>
int CQueue<T>::InitElements(int num)
{
if (elements)
{
delete elements;
}





try{
elements = new T[num];
rear = front = 0;
currentcout = 0;
maxsize = num;
return 0;
}
catch( const bad_alloc& e ){
(void )e;
return -1;
}
}


template<class T>
void CQueue<T>::Destroy()
{
rear = front = 0;
currentcout = 0;
maxsize = 0;


if (elements)
{
delete [] elements;
}
}