C++ queue

🚢 C++ queue (FIFO Data Structure)

std::queue is a container adapter in the C++ STL that follows the FIFO (First In, First Out) principle.
Elements are inserted at the back and removed from the front.


πŸ”Ή 1. Why Use Queue?

  • Task scheduling

  • Printer queues

  • CPU/process scheduling

  • BFS (Breadth-First Search)

  • Customer service systems


πŸ”Ή 2. Include Header

#include <queue>

πŸ”Ή 3. Declaring a Queue

std::queue<int> q;

With underlying container:

std::queue<int, std::deque<int>> q; // default
std::queue<int, std::list<int>> q;

πŸ”Ή 4. Basic Queue Operations

q.push(10); // insert at back
q.push(20);
cout << q.front(); // 10
cout << q.back(); // 20

q.pop(); // removes front


πŸ”Ή 5. Size and Empty Check

q.size();
q.empty();

πŸ”Ή 6. Traversing a Queue

❌ No iterators

βœ” Use a copy:

queue<int> temp = q;

while (!temp.empty()) {
cout << temp.front() << ” “;
temp.pop();
}


πŸ”Ή 7. Queue Example: Simple Simulation

queue<string> customers;

customers.push(“Amit”);
customers.push(“Neha”);

while (!customers.empty()) {
cout << customers.front() << ” served\n”;
customers.pop();
}


πŸ”Ή 8. Queue Example: BFS (Graph)

queue<int> q;
q.push(start);
while (!q.empty()) {
int node = q.front();
q.pop();

for (int next : adj[node]) {
if (!visited[next]) {
visited[next] = true;
q.push(next);
}
}
}


πŸ”Ή 9. Deque vs Queue

Featurequeuedeque
AccessFront & BackFront, Back, Random
InsertBack onlyBoth ends
RemoveFront onlyBoth ends

πŸ”Ή 10. Queue Time Complexity

OperationComplexity
pushO(1)
popO(1)
front/backO(1)

❌ Common Mistakes

q.pop();
cout << q.front(); // ❌ undefined

βœ” Always check:

if (!q.empty())

πŸ”Ή 11. queue vs priority_queue

queuepriority_queue
FIFOHighest priority first
Order preservedSorted by priority
BFSDijkstra, scheduling

πŸ“Œ Summary

  • std::queue follows FIFO

  • Insert at back, remove from front

  • No iterators

  • Built on deque by default

  • Used in scheduling and BFS

You may also like...