**********************************************queue.h*************************************
#ifndef SQUENTIALQUNUE_QUEUE_H #define SQUENTIALQUNUE_QUEUE_H #include <iostream> using namespace std; template <class T> class queue { public: queue(int capacity); void push(const T& a); void pop(); T Front(); T Rear(); bool isempty(); private: int front; int rear; int capacity; T* Queue; }; template <class T> queue<T>::queue(int capacity) { if (capacity<1) throw "queue capacity must be >0 "; this->capacity=capacity; Queue=new T[capacity]; front=rear=0; } template <class T> void queue<T>::push(const T& a) { // if (rear==capacity-1) // { // rear=0; // } // else 等价于rear=(rear+1)%capacity; // { // rear++; // } rear=(rear+1)%capacity; 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+capacity-start,newqueue+capacity-start); } front=2*capacity-1; rear=capacity-2; capacity*=2; delete[] Queue; Queue=newqueue; } Queue[rear]=a; } template <class T> void queue<T>::pop() { if (isempty()) throw "queue is empty .cannot be delete"; front=(front+1)%capacity; Queue[front].~T(); } template <class T> T queue<T>::Front() { return Queue[front+1]; } template <class T> T queue<T>::Rear() { return Queue[rear]; } template <class T> bool queue<T>::isempty() { return rear==front; } #endif //SQUENTIALQUNUE_QUEUE_H
***************************************.cpp**************************
#include <iostream> //先进先出 或者后进后出 //队首 队尾 //对列的操作 //1.push 2.pop 3.front 4.rear 5.isempty #include "queue.h" int main() { queue<int> q(12); q.push(5); q.push(9); q.push(11); q.pop(); cout<<q.Rear()<<endl; cout<<q.Front()<<endl; cout<<"-----------------"<<endl; cout<<q.isempty()<<endl; return 0; }