C++ deque
In this page:
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?
#include <iostream>
#include <deque>
int main() {
std::deque<int> d = {1, 2, 3};
std::cout << d[0] << " " << d.front() << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
#include <deque>
int main() {
std::deque<int> d = {10, 20, 30};
std::cout << d[1] << " " << d.at(2) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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 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: