C++用数组实现的静态队列

#ifndef _STATIC_QUEUE_H_
#define _STATIC_QUEUE_H_

// 静态queue模板,用数组实现的队列,在初始化的时候需要指定长度
template<class T>
class Static_Queue{
public:
	Static_Queue(unsigned int size);
	virtual ~Static_Queue();
	bool push(T t);
	bool pop(T &t);
	unsigned int GetElementCnt();
	void dump();
private:
	unsigned int m_nSize;
	T *m_arrT;
	unsigned int m_nHead;
	unsigned int m_nTail;
	unsigned int m_nEmptyCnt;
};

template<class T>
Static_Queue<T>::Static_Queue(unsigned int size)
{
	m_nSize = size;
	m_arrT = new T[m_nSize];
	memset(m_arrT,0,sizeof(T)*m_nSize);
	m_nHead = 0;
	m_nTail = 0;
	m_nEmptyCnt = m_nSize;
}

template<class T>
Static_Queue<T>::~Static_Queue()
{
	delete[] m_arrT;
	m_arrT = NULL;
}

template<class T>
bool Static_Queue<T>::push(T t)
{
	if( m_nEmptyCnt <= 0 )
	{
		return false;
	}
	m_arrT[m_nTail++] = t;
	if(m_nTail >= m_nSize)
	{
		m_nTail = 0;
	}
	m_nEmptyCnt--;
	return true;
}

template<class T>
bool Static_Queue<T>::pop(T &t)
{
	if( m_nEmptyCnt >= m_nSize )
	{
		return false;
	}
	t = m_arrT[m_nHead++];
	if( m_nHead >= m_nSize )
	{
		m_nHead = 0;
	}
	m_nEmptyCnt++;
	return true;
}

template<class T>
unsigned int Static_Queue<T>::GetElementCnt()
{
	return m_nSize - m_nEmptyCnt;
}

template<class T>
void Static_Queue<T>::dump()
{
	cout<<"head= "<<m_nHead<<" "<<"tail= "<<m_nTail<<endl;
	cout<<"[";
	for(int i = 0;i < m_nSize;i++ )
	{
		cout<<m_arrT[i]<<" ";
	}
	cout<<"]"<<endl;
}

#endif

  测试代码:

#include <iostream>
#include "StaticQueue.h"
using namespace std;

int main()
{
	int i = 0;
	int arr[] = {0,1,2,3,4,5,6,7,8,9};
	Static_Queue<int> qu(8);
	for(i = 0;i<10;i++)
	{
		if(qu.push(arr[i]) == false)
		{
			cout<<"push "<<arr[i]<<" fail"<<endl;
		}
	}
	for(i  = 0;i < 5;i++)
	{
		int t = 0;
		if(qu.pop(t) == true)
		{
			cout<<"pop "<<t<<endl;
		}
	}
	for(i = 0;i<10;i++)
	{
		if(qu.push(arr[i]) == false)
		{
			cout<<"push "<<arr[i]<<" fail"<<endl;
		}
	}
	for(i  = 0;i < 10;i++)
	{
		int t = 0;
		if(qu.pop(t) == true)
		{
			cout<<"pop "<<t<<endl;
		}
	}
	return 0;
}

  

 

posted @ 2015-09-26 15:07  你好阿汤哥  Views(678)  Comments(0Edit  收藏  举报