C++ Queue

🚶‍♂️ C++ Queue – First In, First Out (FIFO) Magic

A queue in C++ works just like a real-life queue: the first person in is the first person out! 🧃

It’s great for tasks like processing data in the order it comes.

📦 How to Use queue in C++

We need the header <queue> to use queues:

#include <queue>
using namespace std;

queue<int> myQueue;

🔧 Example: Basic Queue Operations

#include <iostream>
#include <queue>
using namespace std;

int main() {
    queue<int> q;

    q.push(10); // Add to queue
    q.push(20);
    q.push(30);

    cout << "Front: " << q.front() << endl;
    cout << "Back: " << q.back() << endl;

    q.pop(); // Remove front item

    cout << "After pop, front: " << q.front() << endl;

    return 0;
}
  

Try It Now

🛠️ Common Queue Functions

  • push() – Add to the back
  • pop() – Remove from the front
  • front() – Get the front item
  • back() – Get the last item
  • empty() – Check if queue is empty
  • size() – Get number of elements

🎯 Example: Queue Check

#include <iostream>
#include <queue>
using namespace std;

int main() {
    queue<int> tasks;

    if (tasks.empty()) {
        cout << "No tasks to do!" << endl;
    }

    tasks.push(101);
    tasks.push(102);

    cout << "Tasks in queue: " << tasks.size() << endl;

    return 0;
}
  

Try It Now

✅ Summary

  • Queue = First In, First Out (FIFO)
  • Perfect for jobs that must be done in order
  • Use <queue> header and simple functions to manage