In C++, std::list::pop_back() removes the last element of a std::list. The last node is unlinked and destroyed, and the list becomes one element shorter.
It does not give you the removed value. To use the value, read it first with back(). Include <list> to use it.
This is a member of std::list<T>, a doubly linked list. Every element lives in its own node with a link to the previous and the next node, so a list can insert and erase anywhere quickly once you hold an iterator. It has no access by index, so l[i] does not exist.
Syntax
Call pop_back with empty brackets. Check that the list is not empty first.
C++
int last = l.back(); // read first
l.pop_back(); // then remove it
Call
What it does
l.pop_back()
Removes the last element. size() becomes one smaller.
pop_back() is like a stack “pop” that returns nothing. Read with back(), then pop.
Library declarations
C++
void pop_back();
Parameters
Parameter
Description
None
pop_back() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
Nothing
pop_back() returns void. The removed element is destroyed.
C++ Examples
Example 1 — pop_back() Removes the Last Element
Take the last number off a list of three.
C++
#include <iostream>
#include <list>
int main() {
std::list<int> l = {1, 2, 3};
l.pop_back();
for (int n : l) {
std::cout << n << ' ';
}
std::cout << "(size " << l.size() << ")\n";
return 0;
}
Output
1 2 (size 2)
How It Works
The list holds 1 2 3. The last node is the one with 3.
pop_back() unlinks that node and destroys it. The nodes before it are not touched.
The loop prints 1 2, and size() shows 2.
Example 2 — pop_back() in a while Loop
Read the last element, then remove it, until the list is empty. The loop is safe because it checks empty().