队列(数组形式)实现_c++

来源:互联网 发布:大数据金融行业运用 编辑:程序博客网 时间:2024/06/05 20:34
template<class T> class Queue{friend ostream& operator<< <T> (ostream&, const Queue<T>&);public:Queue(int maxcount = 10):head(0),tail(0), count(maxcount){data = new T[count]();}Queue(const Queue& rhs):head(rhs.head), tail(rhs.tail), count(rhs.count){data = new T[count]();memcpy(data, rhs.data, sizeof(T)*count);}Queue& operator=(const Queue& rhs){if (this == &rhs){return *this;}head = rhs.head;tail = rhs.tail;count = rhs.count;delete []data;data = new T[count]();memcpy(data, rhs.data, sizeof(T)*count);return *this;}~Queue(){delete []data;}T& Front() const;void Push(const T&);void Pop();size_t Size() const;inline bool Empty() const;inline bool Full() const;private:int head;int tail;int count;T* data;};template<class T> T& Queue<T>::Front() const{if (Empty()){exit(1);}return data[head];}template<class T> void Queue<T>::Push(const T& val){if (!Full()){data[tail] = val;tail = (tail+1)%count;}}template<class T> void Queue<T>::Pop(){if (!Empty()){head = (head+1)%count;}}template<class T> size_t Queue<T>::Size() const{return (tail-head+count)%count;}template<class T> bool Queue<T>::Empty() const{return head == tail;}template<class T> bool Queue<T>::Full() const{return (tail+1)%count == head;}template<class T> ostream& operator<<(ostream& os, const Queue<T>& q){if (!q.Empty()){for (int i = q.head; i != q.tail; i = (i+1)%q.count){os<<q.data[i]<<' ';}}return os;}


                                             
0 0
原创粉丝点击