If a Stack is a pile of pancakes, a Queue is a line of people waiting at a movie theater.
A queue operates on the FIFO (First-In, First-Out) principle. The first person to enter the line is the first person to get their ticket and leave the line. In programming, the first item added to a queue is the first item to be processed.
To use a queue, include the <queue> header.
.push() - Adds an element to the back of the queue..pop() - Removes an element from the front of the queue..front() - Returns the first element (the one next to be processed)..back() - Returns the last element added.#include <iostream> #include <queue> using namespace std;int main() { queue<string> printJobs;
// Add jobs to the queue printJobs.push("Document1.pdf"); printJobs.push("Image_final.png"); printJobs.push("Invoice.docx");
// Display the next job in line cout << "Currently printing: " << printJobs.front() << "\n";
// Finish the first job, remove it from the line printJobs.pop();
cout << "Up next: " << printJobs.front() << "\n";
return 0; }
Queues are essential for scenarios where order of arrival matters:
Which method is used to remove an item from a queue?