这是一个环形的队列,为了逻辑简单,队首是一个空字节。
代码:
#ifndef _MYQUEUE_H
#define _MYQUEUE_H
#include <algorithm>
template<class T>
class MyQueue
{
public:
MyQueue(int size = 10);
MyQueue(const MyQueue<T>& OldQueue);
bool IsEmpty();
void Push(const T& item);
void Pop();
T& GetFront();
T& GetRear();
~MyQueue();
const MyQueue<T>& operator= (const MyQueue<T>& OldQueue);
private:
int front;//队首
int rear;//队尾
int capacity;
T* queue;
};
template<class T>
MyQueue<T>::MyQueue(int size)
: capacity(size), front(0), rear(0)
{
queue = new T[capacity];
}
template<class T>
MyQueue<T>::MyQueue(const MyQueue<T>& OldQueue)
{
this->queue = new T[OldQueue.capacity];
this->capacity = OldQueue.capacity;
this->front = OldQueue.front;
this->rear = OldQueue.rear;
std::copy(OldQueue.queue, (OldQueue.queue) + OldQueue.capacity, this->queue);
}
template<class T>
bool MyQueue<T>::IsEmpty()
{
return front == rear;
}
template<class T>
void MyQueue<T>::Push(const T& item)//(rear + 1) % capacity这是一个极为巧妙地操作
{
if ((rear + 1) % capacity == front)//判断是否存满
{
T* temp = new T[capacity * 2];
if (rear > front)//顺序结构
{
std::copy(queue + front, queue + capacity, temp);
}
else//回环结构
{
std::copy(queue + front, queue + capacity, temp);
std::copy(queue, queue + front, temp + capacity - front);
}
delete[] queue;//将原来的数组释放掉
front = 0;//更新成员变量
rear = capacity - 1;
capacity = capacity * 2;
queue = temp;
}
rear = (rear + 1) % capacity;
queue[rear] = item;
}
template<class T>
T& MyQueue<T>::GetFront()
{
if (IsEmpty())
{
throw "the queue is enpty";
}
return queue[(front + 1) % capacity];
}
template<class T>
T& MyQueue<T>::GetRear()
{
if (IsEmpty())
{
throw "the queue is enpty";
}
return queue[rear];
}
template<class T>
void MyQueue<T>::Pop()
{
if (IsEmpty())
{
throw "the queue is enpty";
}
front = (front + 1) % capacity;//队首是一个空字节
queue[front].~T();
}
template<class T>
MyQueue<T>::~MyQueue()
{
delete[] queue;
}
template<class T>
const MyQueue<T>& MyQueue<T>::operator= (const MyQueue<T>& OldQueue)
{
delete[] this->queue;
this->queue = new T[OldQueue.capacity];
this->capacity = OldQueue.capacity;
this->front = OldQueue.front;
this->rear = OldQueue.rear;
std::copy(OldQueue.queue, (OldQueue.queue) + OldQueue.capacity, this->queue);;
return OldQueue;
}
#endif // !_MYQUEUE_H
#include <iostream>
#include "MyQueue.h"
using namespace std;
int main()
{
MyQueue<int> q(3);
for (int i = 0; i < 4; ++i)
{
q.Push(i);
}
cout << q.GetFront() << endl;
cout << q.GetRear() << endl;
for (int i = 0; i < 2; ++i)
{
q.Pop();
}
cout << q.GetFront() << endl;
cout << q.GetRear() << endl;
for (int i = 0; i < 29; ++i)
{
q.Push(i);
}
cout << q.GetFront() << endl;
cout << q.GetRear() << endl;
MyQueue<int> a(q);
MyQueue<int> b;
b = a;
return 0;
}
结果:
0
3
2
3
2
28