std::list
std::list<T> is a doubly linked list. Insert and erase at a known iterator are O(1) and do not invalidate other iterators. Indexing is O(n). Prefer std::vector unless you need splice or stable iterators.
Detailed Explanation
A vector stores elements in one block. Inserting at the front moves every element. Erasing in the middle moves the tail. A list stores each element in its own node with prev and next pointers. Insert and erase change a handful of pointers. Existing iterators and references to other elements stay valid.
That is the whole reason list exists. The reasons not to use it are more numerous. Every node is a separate allocation. Walking the list is a pointer chase with no cache locality. operator[] does not exist. size() is O(1) since C++11. Finding the nth element is O(n).
splice moves nodes from one list to another (or within the same list) without copying T. That is the operation a vector cannot match. A work-queue that steals a run of tasks from another list, or an LRU cache that moves a node to the front, is a legitimate list.
std::forward_list is the singly linked variant: smaller nodes, no size(), no reverse iterator, insert_after instead of insert. Use it when you need a stack-like chain and you care about the extra pointer.
push_front, push_back, emplace_front, emplace_back, insert(it, value), erase(it) are the mutators. merge, sort, unique, and reverse are in-place list algorithms; std::sort does not work because list iterators are bidirectional, not random-access. Use lst.sort().
Invalidation: erase invalidates only iterators to the erased element. Insert invalidates nothing. A pointer to an element stays valid until that element is erased.
For almost every "I thought I needed a list" case, a vector plus erase/insert, or a deque, or a vector of indices, is faster. Measure. Students meet list because textbooks draw boxes and arrows. Production C++ meets it in splice-heavy code and almost nowhere else.
Code Examples
#include <iostream>
#include <list>
#include <string>
int main() {
std::list<std::string> jobs{"parse", "render"};
jobs.push_front("fetch");
auto it = jobs.begin();
++it; // points at "parse"
jobs.erase(it); // other iterators stay valid
for (const auto& j : jobs) std::cout << j << ' ';
std::cout << '\n'; // prints: fetch render
}#include <iostream>
#include <list>
int main() {
std::list<int> a{1, 2, 3};
std::list<int> b{8, 9};
a.splice(a.end(), b); // move all nodes from b to a
std::cout << a.size() << ' ' << b.size() << '\n'; // prints: 5 0
}Common Gotchas
Node allocation dominates
inserting a million ints into a list is far slower than into a vector, even though textbook big-O says insert is O(1). The O(1) hides a heap call.
Holding an iterator across `erase` of that element
reseat with the iterator `erase` returns.
Splicing a node into another list does not copy `T`
if you needed a copy, `insert` instead. Splice empties the source range.