std::list is the doubly linked list from the C++ standard library. Each element sits in its own node, and every node points to the one before it and the one after it. Adding or removing an element at a position you already have is cheap. Jumping straight to the fifth element is not, because a list has no index. This guide covers how to create a list, add and remove elements, loop through it, use its built-in operations, and decide when it is the right choice.
What std::list is
A std::list is a template, so you name the element type when you declare it, such as std::list<int> or std::list<std::string>. It is declared in the <list> header and lives in the std namespace.
Each node stores one value plus pointers to its neighbors. That adds memory per element, and the elements are not stored side by side the way a std::vector stores them. If the idea of nodes and pointers is new to you, the question “What is a linked list in C?” has a short answer you can read first.
The iterators a list provides are bidirectional. You can step forward and backward one element at a time with ++ and --, but you cannot add a number to an iterator to jump several places at once. Use std::next and std::prev from <iterator> for that.
Create a list and loop through it
#include <iostream>
#include <list>
int main() {
std::list<int> scores = {72, 85, 90};
scores.push_front(60);
scores.push_back(95);
for (int score : scores) {
std::cout << score << '\n';
}
}
The brace list sets the starting elements. The range-based for loop works because a list has begin() and end(). The program prints:
60
72
85
90
95
Add and remove elements at the ends
push_front and push_back add an element at the start or the end. pop_front and pop_back remove one. All four run in constant time, so they do not slow down as the list grows.
pop_front and pop_back do not return the value they remove. Read it with front() or back() first:
std::list<int> queue = {1, 2, 3};
int first = queue.front(); // 1
queue.pop_front(); // queue now holds 2, 3
Use size() to count the elements and empty() to check whether the list has any.
Insert and erase with iterators
To insert or erase in the middle, you need an iterator that points to the spot. insert places a new element before that position. erase removes the element at that position and returns an iterator to the element after it.
#include <iostream>
#include <iterator>
#include <list>
#include <string>
int main() {
std::list<std::string> tasks = {"write", "test", "ship"};
auto second = std::next(tasks.begin()); // points to "test"
tasks.insert(second, "plan"); // "plan" goes before "test"
tasks.erase(second); // removes "test"; second is no longer valid
for (const std::string& task : tasks) {
std::cout << task << '\n';
}
}
This prints write, plan and ship. Two rules matter here:
- Inserting does not invalidate existing iterators.
- Erasing invalidates only the iterator to the element that was removed.
When you remove elements while you loop, let erase move the iterator for you. Given a list of ints called numbers, this loop removes the even values:
for (auto it = numbers.begin(); it != numbers.end(); ) {
if (*it % 2 == 0) {
it = numbers.erase(it); // erase returns the next iterator
} else {
++it;
}
}
Built-in operations
std::list has member functions for work that suits its linked structure, or that the generic algorithms cannot do on a list:
sort()sorts the list. Use it instead ofstd::sort.unique()removes consecutive duplicates. Sort first to remove every duplicate.remove(value)erases every element equal tovalue.remove_if(predicate)erases every element for which the predicate returns true.merge(other)merges two sorted lists into one and leavesotherempty.splice(position, other)moves elements fromotherinto this list without copying them.
std::list<int> numbers = {4, 1, 3, 1, 2};
numbers.sort(); // 1, 1, 2, 3, 4
numbers.unique(); // 1, 2, 3, 4
numbers.remove(3); // 1, 2, 4
numbers.remove_if([](int n) { return n > 2; }); // 1, 2
std::list<int> a = {1, 2};
std::list<int> b = {3, 4};
a.splice(a.end(), b); // a now holds 1, 2, 3, 4; b is empty
Accessing elements
A list has no index operator, so numbers[1] does not compile. front() and back() reach the ends directly. For any other position, walk there with an iterator. Reaching the nth element takes n steps, so access by position takes linear time.
std::list<int> numbers = {10, 20, 30};
// numbers[1] = 5; // does not compile: std::list has no operator[]
auto second = std::next(numbers.begin()); // points to 20
*second = 5; // numbers now holds 10, 5, 30
std::list or std::vector?
std::vector is the default choice for most programs. It stores elements in one contiguous block, gives fast access by index, and adds elements at the end quickly. Choose std::list when:
- You insert or erase in the middle often, and you already have an iterator to the spot.
- You need iterators and references to other elements to stay valid while the list changes.
- You want to move a range of elements from one list to another with
splice.
Finding the spot is still a linear search, so the fast insert or erase applies once you have the iterator. For typical sizes, a vector is also often faster even when you insert in the middle, because contiguous memory works better with the processor’s cache. Measure your own code before you choose std::list for speed.
The question “Should I use list or array?” comes up often, and these trade-offs are the core of the answer.
Common mistakes
- Calling
std::sorton a list.std::sort(numbers.begin(), numbers.end())does not compile, becausestd::sortneeds random-access iterators. Usenumbers.sort()instead. - Indexing with
[]. Use an iterator orstd::nextinstead. - Using an iterator after its element is erased. Use the iterator that
erasereturns from then on. - Forgetting the header. Without
#include <list>, the compiler reports thatlistis not a member ofstd.
Key takeaways
std::listis a doubly linked list declared in<list>.- Adding and removing at a known position is cheap. Finding that position and accessing elements by index are not.
- Member functions such as
sort,remove,unique,mergeandsplicecover common list work. - Start with
std::vectorunless you have a specific reason to use a list, and measure when speed matters.