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

c++
762
2024/7/28 10:21:28
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

#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判满等。通过模板类的方式实现,可以支持不同类型的元素入队和出队操作。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++读取文件要注意哪些事项