使用循环数组高效地实现队列类
作者:互联网
#include <iostream> #include <vector> //when array has maxSize-1 elements, it is full template <typename Object> class circularArray { private: std::vector<Object> vt; int front; int back; int maxSize; public: circularArray() { maxSize=50; vt.resize(maxSize); front=0; back=0; } circularArray(int n) :maxSize(n) { vt.resize(maxSize); front=0; back=0; } ~circularArray() { while(front!=back) dequeue(); } circularArray(const circularArray& rhs) { maxSize=rhs.maxSize; vt.resize(rhs.maxSize); front=rhs.front; back=rhs.back; for(int i=0;i!=maxSize-1;++i) vt[i]=rhs.vt[i]; } const circularArray& operator=(const circularArray& rhs) { if(this==&rhs) return *this; *this(rhs); return *this; } void enqueue(const Object& x) { if((back+1)%maxSize==front) { std::cout << "queue is full\n"; return; } vt[back]=x; back=(back+1)%maxSize; } const Object& dequeue() { if(front==back) { std::cout << "empty queue\n"; return Object(); } Object x = vt[front]; front=(front+1)%maxSize; return x; } void print() { for(int i=front;i!=back;) { std::cout << vt[i] << ' '; i=(i+1)%maxSize; } std::cout << '\n'; } }; int main() { circularArray<int> cai; cai.enqueue(5); cai.enqueue(6); cai.enqueue(7); cai.enqueue(8); cai.dequeue(); cai.print(); circularArray<int> cai2=cai; cai2.print(); return 0; }
标签:高效,队列,rhs,cai,back,maxSize,数组,front,circularArray 来源: https://www.cnblogs.com/lhb666aboluo/p/12837320.html