C++实现一个队列
#include <iostream>
#include <string>
#include <queue>
using namespace std;
//.h文件
typedef int q_size;
template <class T>
class CQueue
{
public:
CQueue():pBuffer(NULL),m_len(0)
{
pBuffer = new T[512];
if (!pBuffer)
{
cout<<"pBuffer malloc error!"<<endl;
}
}
~CQueue()
{
if(pBuffer)
{
delete[] pBuffer;
pBuffer = NULL;
}
}
void _q_push(T t);
T _q_pop();
T _q_front();
T _q_back();
void _q_display();
void _q_displayEx();
bool _q_isEmpty();
q_size _q_size();
public:
T *pBuffer;
int m_len;
};
//.cpp文件
template<class T>
void CQueue<T>::_q_push(T t)
{
pBuffer[m_len++] = t;
}
template<class T>
T CQueue<T>::_q_pop()
{
if(m_len == 0)
{
return -1;
}
int i = 0;
T pop = pBuffer[0];
m_len--;
while(i++ < m_len)
{
pBuffer[i - 1] = pBuffer[i];
}
return pop;
}
template<class T>
T CQueue<T>::_q_front()
{
if(m_len == 0)
{
return -1;
}
return pBuffer[0];
}
template<class T>
T CQueue<T>::_q_back()
{
if(m_len == 0)
{
return -1;
}
return pBuffer[m_len - 1];
}
template<class T>
bool CQueue<T>::_q_isEmpty()
{
return (m_len == 0) ? false : true;
}
template<typename T>
q_size CQueue<T>::_q_size()
{
return m_len;
}
template<typename T>
void CQueue<T>::_q_display()
{
int i = 0;
if(m_len)
{
while(i < m_len)
{
cout<<pBuffer[i]<<" ";
i++;
}
cout<<endl;
}
}
template<typename T>
void CQueue<T>::_q_displayEx()
{
int i = 0;
if(m_len)
{
while(i < m_len)
{
for(int j = 0; j < 3; j++)
{
cout<<pBuffer[i][j]<<" ";
}
cout<<endl;
i++;
}
cout<<endl;
}
}
//main
int main()
{
CQueue<int> oQuene;
//CQueue<int> *oQuene = new CQueue<int>();
bool bo = oQuene._q_isEmpty();
cout<<"bo:"<<bo<<endl;
oQuene._q_push(10);
oQuene._q_push(20);
oQuene._q_push(30);
oQuene._q_push(40);
oQuene._q_push(50);
oQuene._q_display();
cout<<"oQuene ' size: "<<oQuene._q_size()<<endl;
oQuene._q_pop();
oQuene._q_pop();
oQuene._q_display();
oQuene._q_push(510);
oQuene._q_push(520);
oQuene._q_push(530);
oQuene._q_display();
cout<<"oQuene ' size: "<<oQuene._q_size()<<endl;
int ifront = oQuene._q_front();
cout<<"ifront:"<<ifront<<endl;
int inear = oQuene._q_back();
cout<<"inear:"<<inear<<endl;
bool boo = oQuene._q_isEmpty();
cout<<"boo:"<<boo<<endl;
CQueue<int*> oDQuene;
int ar0[5] = {10,20,30};
int ar1[3] = {40,50,60};
int ar2[3] = {70,80,90};
int ar3[3] = {100,200,300};
int ar4[3] = {400,500,600};
oDQuene._q_push(ar0);
oDQuene._q_push(ar1);
oDQuene._q_push(ar2);
oDQuene._q_push(ar3);
oDQuene._q_push(ar4);
oDQuene._q_displayEx();
cout<<"oDQuene ' size: "<<oDQuene._q_size()<<endl;
return 0;
}