순서 대기열의 클래스 템플릿과 일반 프로그래밍

3035 단어
#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;
}

좋은 웹페이지 즐겨찾기