What is Queue in C++: Explanation and Example
queue is a container adapter that follows the First-In-First-Out (FIFO) principle, where elements are added at the back and removed from the front. It is used to manage data in the order it arrives, like a line of people waiting their turn.How It Works
A queue in C++ works like a real-life queue or line, such as people waiting at a ticket counter. The first person to get in line is the first one to be served and leave the line. Similarly, the first element added to the queue is the first one to be removed.
Internally, C++ queues use other containers like deque or list to store elements. You can only add elements at the back using push() and remove elements from the front using pop(). This keeps the order intact and prevents random access to elements in the middle.
Example
This example shows how to create a queue of integers, add elements, and remove them in FIFO order.
#include <iostream> #include <queue> int main() { std::queue<int> q; // Add elements to the queue q.push(10); q.push(20); q.push(30); // Process and remove elements while (!q.empty()) { std::cout << q.front() << " "; // Show front element q.pop(); // Remove front element } return 0; }
When to Use
Use a queue when you need to process items in the exact order they arrive. This is common in scenarios like:
- Handling tasks in a printer or CPU scheduler
- Managing requests in web servers
- Simulating real-world lines or waiting lists
- Breadth-first search in graphs
Queues help keep things fair and organized by ensuring first-come, first-served processing.
Key Points
- FIFO order: First element added is first removed.
- Operations: Use
push()to add,pop()to remove, andfront()to access the first element. - No random access: You cannot access elements in the middle directly.
- Underlying container: Usually uses
dequeby default for efficient operations.
Key Takeaways
push() to add and pop() to remove elements in order.deque, providing efficient operations.