-->

C++ - C++ Queues Part 5: Advanced Queue Operations and Best Practices

Queues can be combined with other STL components for complex applications.

Examples

Using Queue for Level-Order Traversal (Binary Tree)

struct Node {

    int data;

    Node* left;

    Node* right;

};

void levelOrder(Node* root) {

    if (!root) return;

    std::queue<Node*> q;

    q.push(root);

    while (!q.empty()) {

        Node* current = q.front();

        q.pop();

        std::cout << current->data << " ";

        if (current->left) q.push(current->left);

        if (current->right) q.push(current->right);

    }

}

Explanation: Level-order traversal visits each level of a binary tree sequentially.

Simulating a Call Center with Multiple Agents

struct Call {

    std::string customer;

    int priority;

};

std::queue<Call> callQueue;

callQueue.push({"Customer1", 2});

callQueue.push({"Customer2", 1});

while (!callQueue.empty()) {

    std::cout << "Handling " << callQueue.front().customer << std::endl;

    callQueue.pop();

}

Explanation: Call queues process customers in the order they arrive.

Implementing a Circular Queue

class CircularQueue {

    int size, front, rear;

    int *arr;

public:

    CircularQueue(int s) : size(s), front(-1), rear(-1) {

        arr = new int[s];

    }

    void enqueue(int value) {

        if ((rear + 1) % size == front) return; // Queue full

        rear = (rear + 1) % size;

        arr[rear] = value;

    }

    void dequeue() {

        if (front == rear) return; // Queue empty

        front = (front + 1) % size;

    }

};

Explanation: Circular queues optimize memory usage in queue-based applications.