C++队列模板的实现

承接上一篇对列的实现,采用模板的方法,来适应各种类型的对列元素。

#ifndef _CMYQUE_H_
#define	_CMYQUE_H_

// class MyQue{
//  
//public:	
//	MyQue(int size); 
//	~MyQue();
//	bool Read(int* num);
//	bool Wirte(int num);//写入
//	void Clear();
//	bool IsFull();
//	bool IsEmpty();
//	int Size();
//private:
//	int len;
//	int SIZE;
//	int w_ptr;
//	int r_ptr;
//	int* Que;
//};

 
template<class T>
class MyQue{
  
public:	
	MyQue(int size) ;
	~MyQue();
	bool Read(T* num);
	bool Wirte(T num);//写入
	void Clear();
	bool IsFull();
	bool IsEmpty();
	int Size();
private:
	int len;
	int SIZE;
	int w_ptr;
	int r_ptr;
	T* Que;
};

template<class T>

MyQue<T>::MyQue(int size)
{
	len = 0;
	w_ptr = 0;
	r_ptr = 0;
	SIZE = size;
	Que = new T[SIZE];
}

template<class T>
MyQue<T>::~MyQue()
{
   delete[] Que;
}

template<class T>
bool MyQue<T>::IsEmpty()
{
	if(len == 0)
	return true;
	else
	return false;
}

template<class T>
bool MyQue<T>::IsFull()
{
	if(len == SIZE)
	return true;
	else
	return false;
}

template<class T>
int MyQue<T>::Size()	 //获取队列长度
{
	return len;
}
 //int 的字符长度有限制,如果重复使用一直增加的话可能会导致数组指针错误	超出int 最大值变为负数
template<class T>
bool MyQue<T>::Wirte(T num)	
{							 
	if(len == SIZE) //满了
	  return false;

	w_ptr = w_ptr%SIZE;	//这样就不超出int范围,大小一直保持在 0-SIZE 之间

	Que[w_ptr] = num; //循环使用数组

	len +=1;		//长度加1
	w_ptr += 1;		//下标+1
	return true;
}

template<class T>
bool MyQue<T>::Read(T* num)
{
   if(len == 0)
	  return false;
	r_ptr = r_ptr%SIZE;
    *num = Que[r_ptr];
	r_ptr += 1;
	len --;
	return true;
}

template<class T>
void MyQue<T>::Clear()	//清空指针 使其复用即可
{
   	len = 0;
	r_ptr = 0;
	w_ptr = 0;
	return ;
}

#endif

这里为什么要把函数具体实现放在头文件里是因为,函数模板要在实例化后才能成为真正的函数,在使用函数模板的源文件里包含函数模板的头文件,如果该文件只有声明,没有定义,那么编译器将无法实例化该模板,最终导致链接错误,编译不过去。所以这里放在一起实现(关于可以分离实现的方法暂不研究)。

main函数文件测试:

#include "CMyque.h"
#include <stdio.h>
int pwer(int m ,int n)
{
  int t = 1;
  if(n>0)
	 t = m*pwer(m,--n);
 return t;
}

int main(int argc,char*argv)
{
	MyQue<int> q(5);
	for(int m = 0 ; m<5;m++)
	 q.Wirte(m);
	//int kk = 0;
	//kk = pwer(2,31);//此时获取值为负数
	//int qq = kk%5;

	for(int m = 0 ; m<3;m++)
	{	
		int n;
		q.Read(&n);
		printf("数组元素:%d 出队,序号:%d \n",n,m);
	}
	printf("此时数组大小为:%d \n",q.Size());
	for(int m = 10 ; m<15;m++)
	{
		q.Wirte(m);
	}
	printf("此时数组大小为:%d \n",q.Size());
	for(int m = 0 ; m<5;m++)
	{	
		int n = 0;
		q.Read(&n);
		printf("数组元素:%d 出队,序号:%d \n",n,m);
	}
	getchar();
	return 0;
}

测试结果:

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值