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

C++ deque

What is a deque?

A deque, short for double-ended queue, is a sequence container that behaves like a hybrid of a vector and a linked list: it offers fast insertion and removal at both ends while still supporting direct random-access indexing like a vector does.

Example: What is a deque?

cpp
#include <iostream>
#include <deque>

int main() {
	std::deque<int> d = {1, 2, 3};
	std::cout << d[0] << " " << d.front() << std::endl;
	return 0;
}

Fast Inserts at Front and Back

Unlike a vector, a deque supports adding elements to its front in constant time using push_front(), in addition to the push_back() you'd already expect — a capability vectors simply don't offer efficiently.

Example: Fast Inserts at Front and Back

cpp
#include <iostream>
#include <deque>

int main() {
	std::deque<int> d = {2, 3};
	d.push_front(1);
	d.push_back(4);
	for (int x : d) std::cout << x << " ";
	std::cout << std::endl;
	return 0;
}

Accessing Elements in Deque

Because a deque supports random access, you can reach any element directly through index brackets like d[i], or through the bounds-checked at() method, exactly the same way you would with a vector.

Example: Accessing Elements in Deque

cpp
#include <iostream>
#include <deque>

int main() {
	std::deque<int> d = {10, 20, 30};
	std::cout << d[1] << " " << d.at(2) << std::endl;
	return 0;
}

Removing Elements from Deque

You can remove elements from either end of a deque using pop_front() or pop_back(), and both operations automatically update the container's reported size, mirroring how push and pop work at the opposite end.

Example: Removing Elements from Deque

cpp
#include <iostream>
#include <deque>

int main() {
	std::deque<int> d = {1, 2, 3};
	d.pop_front();
	d.pop_back();
	std::cout << d.size() << std::endl;
	return 0;
}

Iterating over Deque

Just like a vector, a deque can be traversed with an index-based loop, a range-based for loop, or STL iterators — the uniform iteration interface is one of the main benefits of building on the STL's shared container conventions.

Example: Iterating over Deque

cpp
#include <iostream>
#include <deque>

int main() {
	std::deque<int> d = {1, 2, 3};
	for (int i = 0; i < d.size(); i++) std::cout << d[i] << " ";
	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.