C++设计一个循环队列QUEUE<T>
时间: 2023-05-27 09:02:29 浏览: 113
C++实现循环队列
以下是以C++语言实现的循环队列QUEUE<T>的示例代码:
```c++
template <typename T>
class Queue {
private:
T *data;
int front, rear, size;
public:
Queue(int init_size = 10): data(new T[init_size]), front(0), rear(0), size(init_size) {};
bool isEmpty() const {
return front == rear;
}
bool isFull() const {
return (rear + 1) % size == front;
}
int getSize() const {
return (rear - front + size) % size;
}
void enqueue(const T& obj) {
if (isFull()) {
T *newData = new T[2 * size];
int j = 0;
for (int i = front; i != rear; i = (i + 1) % size) {
newData[j++] = data[i];
}
newData[j++] = data[rear];
front = 0;
rear = j - 1;
size *= 2;
delete [] data;
data = newData;
}
data[rear] = obj;
rear = (rear + 1) % size;
}
T dequeue() {
if (isEmpty()) {
throw std::underflow_error("Queue empty");
}
T obj = data[front];
front = (front + 1) % size;
return obj;
}
};
```
该循环队列QUEUE<T>支持动态扩容,当队列满时会将队列大小扩充为原大小的两倍,同时将队列中的元素复制到新的内存中,并删除原有内存。如果队列为空,则出队列操作会抛出std::underflow_error异常。
阅读全文