In C++, std::deque::pop_front() removes the first element of a std::deque. The size becomes one smaller, and the second element becomes the new first element.
This is one of the main reasons to use a deque. A std::vector has no pop_front(), because removing the first element of a vector moves every other element. Include <deque> to use it.
This is a member of std::deque<T>, a double-ended queue. A deque is fast at adding and removing at both ends, and it allows access by index like std::vector. Unlike a vector, its elements are stored in several blocks, not in one contiguous block.
Syntax
Call pop_front with empty brackets. It takes no arguments.
C++
d.pop_front();
Call
What it does
d.pop_front()
Removes the first element and makes the deque one element shorter.
The back version is pop_back(). To add at the front, use push_front().
Library declarations
C++
void pop_front();
Parameters
Parameter
Description
None
pop_front() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
Nothing
pop_front() returns void. The removed value is destroyed.
C++ Examples
Example 1 — Basic pop_front()
Remove the first number and print what is left.
C++
#include <deque>
#include <iostream>
int main() {
std::deque<int> d = {1, 2, 3};
d.pop_front();
for (int n : d) {
std::cout << n << ' ';
}
std::cout << "(front is now " << d.front() << ")\n";
return 0;
}
Output
2 3 (front is now 2)
How It Works
The deque starts as 1 2 3, with 1 at the front.
pop_front() removes 1. The other elements do not need to be moved.
2 is now the first element, which front() confirms.
Example 2 — Remove Values While a Condition Is True
In a sorted deque, drop all the small values from the front.
C++
#include <deque>
#include <iostream>
int main() {
std::deque<int> d = {1, 3, 5, 12, 20};
while (!d.empty() && d.front() < 10) {
d.pop_front();
}
for (int n : d) {
std::cout << n << ' ';
}
std::cout << '\n';
return 0;
}
Output
12 20
How It Works
The loop checks !d.empty() first. Then it checks whether the front value is below 10.
The values 1, 3, and 5 are each at the front in turn, and each one is removed by pop_front().
When 12 becomes the front, the condition is false and the loop stops. 12 20 remain.
Example 3 — Read with front(), Then Remove
pop_front() returns nothing, so keep the value before you remove it.