C++ Standard Template Library (STL) Tutorial: Queue
The C++ STL provides a container called a queue, which follows the First-In-First-Out (FIFO) principle. In other words, the first element added to the queue will be the first one to be removed.
Syntax
#include <queue>
std::queue<data_type> my_queue;
Example
#include <iostream>
#include <queue>
using namespace std;
int main() {
queue<int> my_queue;
my_queue.push(5);
my_queue.push(10);
my_queue.push(15);
my_queue.push(20);
cout << "Queue size is: " << my_queue.size() << endl;
while (!my_queue.empty()) {
cout << my_queue.front() << " ";
my_queue.pop();
}
cout << endl << "Queue size is now: " << my_queue.size() << endl;
return 0;
}
Output
Queue size is: 4
5 10 15 20
Queue size is now: 0
Explanation
In the above example, we create a queue of integers and add 4 elements to it using the push() method. We then print the size of the queue using the size() method.
Next, we loop through the queue using the front() method to get the element at the front of the queue, and then remove it using the pop() method. This loop continues until the queue is empty.
Finally, we print the size of the queue again to verify that it is now 0.
Use
Queues are useful when you need to process data in the order that it was added. For example, a print queue that must print documents in the order they were sent to the printer.
Important Points
- A queue is a container that follows the FIFO principle.
- The push() method adds an element to the back of the queue.
- The front() method returns the element at the front of the queue.
- The pop() method removes the element at the front of the queue.
- The size() method returns the number of elements in the queue.
- The empty() method returns true if the queue is empty.
Summary
In summary, the queue container in the C++ STL allows you to implement the queue data structure, which is useful for processing data in the order that it was added. The queue follows the FIFO principle and provides methods for adding, accessing, and removing elements.