C++ queue STL
In this page:
What is std::queue?
std::queue is a container adapter that provides First-In-First-Out (FIFO) access. It wraps an underlying container (deque by default) and restricts access so elements are added at the back and removed from the front.
Example: What is std::queue?
#include <iostream>
#include <queue>
int main() {
std::queue<int> q; // FIFO container adapter
q.push(1);
q.push(2);
std::cout << q.front() << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
push(), pop(), front() and back()
push() adds an element to the back. front() and back() return references to the first and last elements. pop() removes the front element but returns nothing -- read it with front() first if needed.
Example: push(), pop(), front() and back()
#include <iostream>
#include <queue>
int main() {
std::queue<int> q;
q.push(10);
q.push(20);
std::cout << q.front() << " " << q.back() << std::endl;
q.pop(); // removes from the front
std::cout << q.front() << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
FIFO Behavior
The defining property of a queue is that the first element pushed is always the first one popped -- First In, First Out. This models real-world queues, like people waiting in line or tasks waiting to be processed.
Example: FIFO Behavior
#include <iostream>
#include <queue>
int main() {
std::queue<int> q;
q.push(1);
q.push(2);
q.push(3);
std::cout << q.front() << std::endl; // the first one pushed comes out first
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Checking empty() and size()
empty() returns true if the queue has no elements. size() returns the current element count. Always check empty() before calling front(), back(), or pop() to avoid undefined behavior.
Example: Checking empty() and size()
#include <iostream>
#include <queue>
int main() {
std::queue<int> q;
if (q.empty()) { // check before calling front()/pop()
std::cout << "Empty" << std::endl;
}
std::cout << q.size() << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Practical Use: Level-Order Traversal
Queues are the standard tool for breadth-first traversal, such as processing a tree level by level or exploring a graph in BFS order.
Example: Practical Use: Level-Order Traversal
#include <iostream>
#include <queue>
int main() {
std::queue<int> q; // simulates BFS: process level by level
q.push(1);
while (!q.empty()) {
int node = q.front();
q.pop();
std::cout << node << " ";
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first: