The std::queue is a container adapter in C++ that provides a FIFO (First-In-First-Out) data structure. Elements are inserted at the back and removed from the front, making it ideal for scenarios like task scheduling or buffer management.
📌 Common Operations in std::queue
1. push(val)
Adds a new element val to the back of the queue.
#include <queue> std::queue<int> q; q.push(10); q.push(20);
2. pop()
Removes the front element of the queue. It does not return the removed element.
q.pop();
3. front()
Returns a reference to the front element of the queue.
std::cout << "Front: " << q.front();
4. back()
Returns a reference to the last (rear) element of the queue.
std::cout << "Back: " << q.back();
5. empty()
Checks whether the queue is empty. Returns true if empty, otherwise false.
if (q.empty()) {
std::cout << "Queue is empty.";
}
6. size()
Returns the number of elements currently in the queue.
std::cout << "Size: " << q.size();