C++ template class implements circular queue

Written in front:

       This article uses a C++ template class to draw a circular queue. In the implementation process, first use a few pictures to introduce the idea, and then add the code and running results.

 

text:

    Several behaviors of Queue:

 

Then there are code snippets and comments:

 

#include <iostream>

using namespace std;


template<class T>
class Queue
{
public:
	Queue(int defaultCapacity = 10);

	void push(const T &item); //往queue中添加数据

	void pop();				 //从头部删除数据
	bool isEmpty()const;     //判断队列是否为空
	T& Front() const;		 //读取队列头部的数据
	T& Rear()const;			 //读取队列尾部的数据

private:
	int capacity; //容量
	int front;	  //头部index
	int rear;     //尾部index

	T *queue;
};

template <class T>
Queue<T>::Queue(int defaultCapacity)
{
	if (defaultCapacity < 0)
		throw "Queue size must > 0";

	front = rear = 0;			//头部和尾部开始的位置
	capacity = defaultCapacity;
	queue = new T[capacity];
}

template<class T>
void Queue<T>::push(const T&item)
{
	if ((rear + 1) % capacity == front) //队列满了的时候,将队列扩大为原来两倍
	{
		T* pNew = new T [capacity * 2];

		int start = (front + 1) % capacity;

		if (start < 2) //第一种队列满的时候,没有发生回环
		{
			//cout << "1" << endl;
			copy(queue+start,queue+start+capacity-1,pNew);
		}
		else //第二种队列满的时候,发生了回环
		{
			//cout << "2" << endl;
			copy(queue + start, queue + capacity - 1,pNew);
			copy(queue, queue+rear+1, pNew+capacity-start);
		}

		front = 2 * capacity - 1; //front指向末尾
		rear = capacity - 2;      

		capacity *= 2;
		delete[] queue;

		queue = pNew;
	}

	rear = (rear + 1) % capacity;
	queue[rear] = item;
	

}

template <class T>
void Queue<T> ::pop()
{
	if (isEmpty()) throw "queue is empty";

	front = (front + 1) % capacity;

	queue[front].~T(); //将front释放掉


}

template <class T>
inline T& Queue<T>::Front() const
{
	
	if(isEmpty())throw "queue is empty";

	return queue[(front+1)%capacity];
}

template <class T>
inline T& Queue<T>::Rear() const
{
	if (isEmpty())throw "queue is empty";

	return queue[rear];
}

template <class T>
inline bool Queue<T>::isEmpty() const
{
	return rear == front;   //当收尾相等的时候,任务队列是空的
}

int main()
{
	Queue <char>q(4);

	q.push('A');
	q.push('B');
	q.push('C');
	cout << "front:" << q.Front() << ",rear:" << q.Rear() << endl;
	q.push('D');
	q.push('E');
	q.push('F');
	q.push('G');
	cout << "front:" << q.Front() << ",rear:" << q.Rear() << endl;
	q.pop();
	cout << "front:" << q.Front() << ",rear:" << q.Rear() << endl;



	return 0;
}

operation result:

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/weixin_40204595/article/details/106229215