c++

C++循环队列的模板实现

小樊
85
2024-07-14 10:21:28
栏目: 编程语言

#include <iostream>

template <class T>
class CircularQueue {
private:
    int front, rear, maxSize;
    T* queueArray;
public:
    CircularQueue(int size) {
        maxSize = size + 1; // one extra space for checking full condition
        front = rear = 0;
        queueArray = new T[maxSize];
    }

    ~CircularQueue() {
        delete[] queueArray;
    }

    bool isEmpty() {
        return front == rear;
    }

    bool isFull() {
        return (rear + 1) % maxSize == front;
    }

    void enqueue(T item) {
        if (isFull()) {
            std::cout << "Queue is full, cannot enqueue.\n";
        } else {
            rear = (rear + 1) % maxSize;
            queueArray[rear] = item;
        }
    }

    T dequeue() {
        if (isEmpty()) {
            std::cout << "Queue is empty, cannot dequeue.\n";
            return T();
        } else {
            front = (front + 1) % maxSize;
            return queueArray[front];
        }
    }
};

int main() {
    CircularQueue<int> queue(5);

    queue.enqueue(1);
    queue.enqueue(2);
    queue.enqueue(3);

    std::cout << "Dequeued item: " << queue.dequeue() << std::endl;
    std::cout << "Dequeued item: " << queue.dequeue() << std::endl;

    queue.enqueue(4);
    queue.enqueue(5);
    queue.enqueue(6);

    std::cout << "Dequeued item: " << queue.dequeue() << std::endl;
    std::cout << "Dequeued item: " << queue.dequeue() << std::endl;
    std::cout << "Dequeued item: " << queue.dequeue() << std::endl;

    return 0;
}

这段代码实现了一个循环队列的模板类CircularQueue,其中包括了队列的基本操作:enqueue入队、dequeue出队、isEmpty判空、isFull判满等。通过模板类的方式实现,可以支持不同类型的元素入队和出队操作。

0
看了该问题的人还看了