Intermediate6 min readLesson 39 of 50
What is a Queue?
A queue is a FIFO (First-In-First-Out) container. Elements are added at the back and removed from the front — like a ticket line. Include <queue>.
#include <iostream>
#include <queue>
using namespace std;
int main() {
queue<string> customers;
customers.push("Alice"); // enqueue
customers.push("Bob");
customers.push("Carol");
cout << "Queue size: " << customers.size() << endl;
while (!customers.empty()) {
cout << "Serving: " << customers.front() << endl;
customers.pop(); // dequeue
}
return 0;
}
Output:
Queue size: 3
Serving: Alice
Serving: Bob
Serving: Carol
Queue Methods
| Method | Description |
push(val) | Add to back |
pop() | Remove from front |
front() | View front element |
back() | View back element |
empty() | True if queue is empty |
size() | Number of elements |
Priority Queue
A priority_queue always serves the highest-priority (largest by default) element first:
#include <queue>
priority_queue<int> pq;
pq.push(3); pq.push(1); pq.push(5); pq.push(2);
while (!pq.empty()) {
cout << pq.top() << " "; // 5 3 2 1
pq.pop();
}
Exercise
Simulate a print queue: add 5 print jobs to a queue and process them one by one, printing "Printing: [job]" for each.
Show Solution
#include <iostream>
#include <queue>
using namespace std;
int main() {
queue<string> printQueue;
printQueue.push("Report.pdf");
printQueue.push("Invoice.docx");
printQueue.push("Photo.jpg");
printQueue.push("Presentation.pptx");
printQueue.push("Letter.txt");
while (!printQueue.empty()) {
cout << "Printing: " << printQueue.front() << endl;
printQueue.pop();
}
return 0;
}
Quiz
What does FIFO stand for?
- A) First In, Fast Out
- B) First In, First Out
- C) Final In, First Out
- D) First In, Full Out
Answer
B) First In, First Out
Summary
queue is FIFO: push to back, pop from front.- Methods:
push, pop, front, back, empty, size. priority_queue processes the highest-priority element first.