← Back to C++ Course | Chapter 13: STL Containers & Algorithms | Lesson 14 of 15

C++ queue STL

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?

cpp
#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;
}

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()

cpp
#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;
}

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

cpp
#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;
}

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()

cpp
#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;
}

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

cpp
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.