顺序队列的类模板与泛型编程

#ifndef _顺序队列_H
#define _顺序队列_H

template<class T>   // 模板类,T是用来创建动态数组,
class Queue
{
public:
	Queue(int queueCapacity = 10);  // 队列的数量存储10个
	bool IsEmpty() const;  // 这是判断队列是不是空的,
	T& Front() const; // 这个是读取队首的数据,
	T& Rear() const;  // 这个是读取或查看队尾的数据,中间的数据是不能查看或读取的,
	void Push(const T& item);  // 这是将一个数据从队尾压入的队列中,
	void Pop(); // Pop是删除数据,从队首删除,
private:
	T *queue;  // T是用来创建一个动态的数组,
	int front;  // front 是用来记录队首的下标,
	int rear; // rear 是用来记录队尾的下标,
	int capacity; // 是记录数据中数目,
};

template<class T>  // 类模板,
Queue<T>::Queue(int queueCapacity):capacity(queueCapacity)
{
	if(capacity<1) throw "Queue capacity must be > 0";
	queue = new T[capacity];
	front = rear = 0;
}

template<class T>  // 类模板,
inline bool Queue<T>::IsEmpty() const
{
	return front == rear;
}

template<class T>  // 类模板,
void Queue<T>::Push(const T &item)  // 在给队列增加数据的时候,第一个位置是空着的,是为了push和pop的速度快,
{
	//if(rear == capacity - 1)  // 这表示如果队尾到(最后)它的容量了,就将队尾从0开始,否则继续进行加加,
	//	rear = 0;
	//else
	//	rear++;
	if((rear + 1)%capacity == front)  // 队列满了,
	{
		//加倍
		T* newQueue = new T[2*capacity];

		int start = (front + 1) % capacity;
		if(start < 2)  // 没有回转,
			copy(queue + start, queue + start + capacity - 1, newQueue);
		else  // 有回转,
		{
			copy(queue + start, queue + capacity, newQueue);
			copy(queue, queue + rear + 1, newQueue + capacity - start);
		}
		front = 2 * capacity - 1;
		rear = capacity - 2;
		capacity *= 2;
		delete[] queue;
		queue = newQueue;
	}


	rear = (rear + 1) % capacity;
	queue[rear] = item; // 这是将加入的数据放到队尾,
}

template<class T>  // 类模板
inline T& Queue<T>::Front() const  // 这是读队首的位置,
{
	if(IsEmpty()) throw "Queue is empty , no front element";
	return queue[(front + 1) % capacity];   // 第一个数据是空的,将加1 读取队首的位置,
}
template<class T>  // 类模板
inline T& Queue<T>::Rear() const  // 读队尾的位置,
{
	if(IsEmpty()) throw "Queue is empty, No rear element";
	return queue[rear];
}
template<class T>  // 类模板
void Queue<T>::Pop()
{
	if(IsEmpty()) throw "Queue is empty, Canot delete";
	front = (front + 1) % capacity;
	queue[front].~T();
}


#endif
#include <iostream>
#include "顺序队列.h"

using namespace std;

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

	q.Push('x');
	q.Push('i');

	cout << q.Front() << ", " << q.Rear() << endl;
	q.Push('a');
	q.Push('o');
	q.Push('c');
	cout << q.Front() << ", " << q.Rear() << endl;
	/*q.Pop();
	cout << q.Front() << ", " << q.Rear() << endl;*/
	q.Push('u');
	q.Push('i');
	cout << q.Front() << ", " << q.Rear() << endl;
	q.Push('l');
	q.Push('o');
	q.Push('v');
	q.Push('e');
	cout << q.Front() << ", " << q.Rear() << endl;

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值