循環隊列是一種具有固定大小的隊列,當隊列滿時,新元素將會覆蓋最舊的元素。下面是一個簡單的C++循環隊列的應用實例,實現了一個基本的生產者-消費者模型。
#include <iostream>
using namespace std;
#define SIZE 5
class CircularQueue {
private:
int arr[SIZE];
int front, rear;
public:
CircularQueue() {
front = -1;
rear = -1;
}
void enqueue(int value) {
if ((front == 0 && rear == SIZE - 1) || (rear == (front - 1) % (SIZE - 1))) {
cout << "Queue is full" << endl;
} else if (front == -1) {
front = rear = 0;
arr[rear] = value;
} else if (rear == SIZE - 1 && front != 0) {
rear = 0;
arr[rear] = value;
} else {
rear++;
arr[rear] = value;
}
}
int dequeue() {
if (front == -1) {
cout << "Queue is empty" << endl;
return -1;
}
int value = arr[front];
arr[front] = -1;
if (front == rear) {
front = rear = -1;
} else if (front == SIZE - 1) {
front = 0;
} else {
front++;
}
return value;
}
void displayQueue() {
if (front == -1) {
cout << "Queue is empty" << endl;
return;
}
cout << "Elements in the circular queue are:" << endl;
if (rear >= front) {
for (int i = front; i <= rear; i++) {
cout << arr[i] << " ";
}
} else {
for (int i = front; i < SIZE; i++) {
cout << arr[i] << " ";
}
for (int i = 0; i <= rear; i++) {
cout << arr[i] << " ";
}
}
cout << endl;
}
};
int main() {
CircularQueue q;
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.enqueue(4);
q.enqueue(5);
q.displayQueue();
cout << "Dequeued element: " << q.dequeue() << endl;
q.enqueue(6);
q.displayQueue();
return 0;
}
在這個示例中,我們定義了一個CircularQueue
類,實現了循環隊列的基本功能,包括入隊、出隊和顯示隊列元素。在main
函數中,我們演示了如何使用循環隊列模擬生產者-消費者模型。首先入隊5個元素,然后出隊一個元素,最后再入隊一個元素。最終打印出隊列中的元素。