c++佇列類别範本的實現

GeekAdo發表於2014-07-11
//佇列類别範本定義
template <class POINT_TYPE,int MAX_POINTS> 
class VarQueue
{
public:
	VarQueue()
	{
		m_MaxCount=MAX_POINTS;
		m_Count=0;
	}
	VarQueue(unsigned int MaxCount)
	{
		if(MaxCount>MAX_POINTS)
			m_MaxCount=MAX_POINTS;
        else
	     m_MaxCount=MaxCount;
		m_Count=0;
	}
public:
	//出隊處理,先進先出
	unsigned int PopPoint(POINT_TYPE *Point);
	//入隊處理,追加在隊的末尾
	unsigned int AppendPoint(const POINT_TYPE &Point);
	//取得某結點的值
bool GetPoint(POINT_TYPE *Point,unsigned int Position)const;
//取得結點數
unsigned int GetCount()const;
	//清空佇列
	void ClearQueue();
private:
	//佇列的最大結點數
	unsigned int m_MaxCount;
	//佇列的實際結點數
	unsigned int m_Count;
	//儲存結點的陣列
	POINT_TYPE m_Queue[MAX_POINTS];
};

/////////////////佇列元素類定義
class CElement
{
public:
	CElement()
	{
		fValue=0.0;
	}
	CElement(float value)
	{
		fValue=value;
	}
	CElement& operator =(int value)
	{
	  fValue=(float)value;
	  return *this;
	}
	CElement& operator =(float value)
	{
	  fValue=value;
	  return *this;
	}
	CElement& operator =(CElement elem)
	{
	  fValue=elem.fValue;
	  return *this;
	}
	operator float()
	{
		return fValue;	
	}
	float GetValue()const
	{ 
		return fValue;
	}
private:
	float fValue;
};
#include "stdio.h"
#include "Queue.h"
//佇列類别範本的實現
template <class POINT_TYPE,int MAX_POINTS>
unsigned int VarQueue<POINT_TYPE,MAX_POINTS>::PopPoint(POINT_TYPE *Point)
{
	unsigned int i=0;
	if(m_Count>0)
	{  
		if(NULL!=Point)
			*Point=m_Queue[0];
		for(i=1;i<m_Count;i++)
		{
			m_Queue[i-1]=m_Queue[i];
		}
		m_Count--;
	}
	return m_Count;
}

template <class POINT_TYPE,int MAX_POINTS>
unsigned int VarQueue<POINT_TYPE,MAX_POINTS>::AppendPoint(const POINT_TYPE &Point)
{
	if(m_Count<m_MaxCount)
		m_Queue[m_Count++]=Point;		
	
	return m_Count;
}

template <class POINT_TYPE,int MAX_POINTS>
bool VarQueue<POINT_TYPE, MAX_POINTS>::GetPoint(POINT_TYPE *Point,unsigned int Position)const
{
	if(Position<m_Count && NULL!=Point)
	{	  
		*Point=m_Queue[Position];
	    return true;
	}
	else 
		return false;
}

template <class POINT_TYPE,int MAX_POINTS>
inline unsigned int  VarQueue<POINT_TYPE,MAX_POINTS>::GetCount()const
{
	return m_Count;
}

template <class POINT_TYPE,int MAX_POINTS>
void VarQueue<POINT_TYPE,MAX_POINTS>::ClearQueue()
{ 
	m_Count=0;
}

int main(int argc, char* argv[])
{
    /*將模板例項化為最多容納50個元素的整型佇列,類名為VarQueue<int,50>,
	由該類例項化的物件名為iQueue */
	VarQueue<int,50> iQueue(20);
	/*將模板例項化為最多容納50個元素的CElement型佇列,類名為VarQueue <CElement,30>,
	由該類例項化的物件名為fQueue */
	VarQueue<CElement,30> fQueue(10);
	int ival=0;
	unsigned count=0;;
	CElement fval=1.0;
	
	for(unsigned int i=0;i<4;i++)
		iQueue.AppendPoint(i);
	
	count=iQueue.GetCount();
	for( i=0;i<count;i++)
	{
		iQueue.PopPoint(&ival);
		fQueue.AppendPoint((float)ival);
	}
	for( i=0;i<fQueue.GetCount();i++)
	{
		fQueue.GetPoint(&fval,i);
		printf("%4.2f\n",fval.GetValue());
	}
	iQueue.ClearQueue();
	fQueue.ClearQueue();
	return 0;
}


相關文章