循环队列的C++实现

头文件:CircleQueue.hpp

#pragma once
#include<iostream>
using namespace std;

const int QueueSize = 8;

template<class T>
class CircleQueue
{
public:
	CircleQueue() { front = rear = 0; }
	void EnQueue(T d);	//入队
	T DeQueue();		//出队
	int get_length();	//获取队列长度
	T get_front();		//获取队头元素
private:
	int front, rear;
	T data[QueueSize];
};

template<class T>
void CircleQueue<T>::EnQueue(T d)
{
	if ((rear + 1) % QueueSize == front)
		throw "overflow error";
	rear = (rear + 1) % QueueSize;
	data[rear] = d;
}//入队

template<class T>
T CircleQueue<T>::DeQueue()
{
	if (front == rear)
		throw "underflow error";
	front = (front + 1) % QueueSize;
	return data[front];
}//出队

template<class T>
int CircleQueue<T>::get_length()
{
	return ((rear - front + QueueSize) % QueueSize);
}//获取队列长度

template<class T>
T CircleQueue<T>::get_front()
{
	if (front == rear)
		throw "underflow error";
	return data[(front + 1) % QueueSize];
}//获取队头元素

编写main函数测试:

#include"CircleQueue.hpp"


int main()
{
	CircleQueue<int> q;
	for (int i = 1; i < 8; i++)
	{
		q.EnQueue(i);
	}
	//EnQueue异常处理机制测试
	try
	{
		q.EnQueue(8);
	}
	catch (const char* err)
	{
		cout << err << endl;
	}

	while (q.get_length())
		cout << q.DeQueue() << endl;

	//DeQueue异常处理机制测试
	try
	{
		q.DeQueue();
	}
	catch (const char* err)
	{
		cout << err << endl;
	}

	//get_front异常处理机制测试
	try
	{
		q.get_front();
	}
	catch (const char* err)
	{
		cout << err << endl;
	}
	
	
	return 0;
}

 程序运行结果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值