Skip to content

Module 8 · The Standard Template Library — topic 3 of 7

Lists (std::list and std::forward_list)

Doubly and singly linked lists in the STL: constant-time insertion and removal anywhere, splice, member sort and remove_if, and when lists actually beat vectors.

Beginner 12 min read·Lesson 33 of 40 in C++ Programming

Learning objectives

  • Insert and erase in a list with iterators
  • Use list member algorithms (sort, remove_if, splice, unique)
  • Decide between list and vector

Definition

std::list is a doubly linked list and std::forward_list a singly linked list; both allow O(1) insertion and erasure at any position given an iterator, keep iterators to other elements valid, but do not provide random access.

Introduction

A std::list stores each element in its own node with pointers to the previous and next nodes. Inserting in the middle just rewires pointers — no shifting — and existing iterators remain valid.

Why it matters

Lists are the right tool when you hold iterators to elements and insert/remove around them frequently (e.g. LRU caches).

Knowing why vectors are usually faster despite O(n) insertion is a mark of a mature C++ programmer.

Detailed explanation

Operations: push_front, push_back, insert(it, v), erase(it) — all O(1) given an iterator. Finding the position is still O(n).

Lists have member functions because the generic algorithms need random access or would be slower: l.sort(), l.unique(), l.remove_if(pred), l.reverse(), l.merge(other).

splice moves nodes from one list to another in O(1) without copying elements.

forward_list uses less memory (one pointer per node) but supports only forward iteration and insert_after.

Vectors often outperform lists even for middle insertions on modern CPUs because contiguous memory is cache friendly.

Syntax

C++
std::list<int> l{1, 2, 4};
auto it = std::next(l.begin(), 2);
l.insert(it, 3); // 1 2 3 4
l.remove_if([](int x){ return x % 2; });
l.sort();
std::list<int> other{9};
l.splice(l.end(), other); // move nodes
  • Use std::next/std::advance to move iterators.
  • No operator[].
  • Erasing invalidates only the erased element's iterator.

Code examples

Insert in the middle

C++
#include <iostream>
#include <iterator>
#include <list>
int main() {
std::list<int> l{10, 20, 40};
auto it = std::next(l.begin(), 2);
l.insert(it, 30);
l.push_front(5);
for (int x : l) std::cout << x << ' ';
std::cout << "(" << l.size() << ")\n";
return 0;
}
Output
5 10 20 30 40 (5)

Member algorithms

C++
#include <iostream>
#include <list>
int main() {
std::list<int> l{5, 3, 5, 1, 3, 9};
l.sort();
l.unique();
l.remove_if([](int x) { return x > 8; });
for (int x : l) std::cout << x << ' ';
std::cout << '\n';
return 0;
}
Output
1 3 5

More examples

A tiny LRU cache with list + map

C++
#include <iostream>
#include <list>
#include <string>
#include <unordered_map>
class LRU {
public:
explicit LRU(std::size_t cap) : cap_(cap) {}
void put(const std::string& k, int v) {
if (auto it = pos_.find(k); it != pos_.end()) order_.erase(it->second);
order_.push_front({k, v});
pos_[k] = order_.begin();
if (order_.size() > cap_) {
pos_.erase(order_.back().first);
order_.pop_back();
}
}
bool get(const std::string& k, int& out) {
auto it = pos_.find(k);
if (it == pos_.end()) return false;
order_.splice(order_.begin(), order_, it->second); // move to front in O(1)
out = it->second->second;
return true;
}
void show() const { for (const auto& [k, v] : order_) std::cout << k << ' '; std::cout << '\n'; }
private:
std::size_t cap_;
std::list<std::pair<std::string, int>> order_;
std::unordered_map<std::string, std::list<std::pair<std::string, int>>::iterator> pos_;
};
int main() {
LRU c(2);
c.put("a", 1);
c.put("b", 2);
int v;
c.get("a", v);
c.put("c", 3); // evicts b, the least recently used
c.show();
std::cout << c.get("b", v) << '\n';
return 0;
}
Output
c a 
0

Step-by-step explanation

  • The list keeps keys in use order: most recent at the front.
  • The map stores an iterator to each key's node for O(1) access.
  • splice moves the accessed node to the front without invalidating the stored iterator.
  • When capacity is exceeded, the back (least recently used) is evicted.

Expected output

Running “A tiny LRU cache with list + map” prints exactly:

TextOutput
c a
0

Practical applications

  • Caches (browsers, databases) use list + hash map LRU structures.
  • Text editors keep undo histories in lists.
  • Memory allocators link free blocks in lists.

Best practices

  • Use list when you need stable iterators and O(1) splicing.
  • Prefer member algorithms for lists.
  • Measure before replacing vector with list.

Common mistakes

Using std::sort on a list

Avoid

std::sort(l.begin(), l.end());

Prefer

l.sort();

std::sort needs random-access iterators; lists provide only bidirectional ones.

Assuming lists are faster for small data

Avoid

std::list<int> scores; // because I insert sometimes

Prefer

std::vector<int> scores;

Vectors are usually faster due to cache locality; choose list only for iterator stability or splicing.

Important notes

  • Each list node carries two pointers of overhead (forward_list one).
  • std::list::size() is O(1) since C++11.

Key takeaways

  • Lists insert/erase in O(1) given an iterator.
  • Use member sort/unique/remove_if/splice.
  • No random access; vectors usually win on speed.

Try it yourself

  1. 1
    Merge two sorted lists with merge and print the result.
  2. 2
    Implement a playlist with next/previous using std::list iterators.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

3 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhich operation does std::list NOT support?
  • ModerateWhat is printed?
  • AdvancedWhat is printed?
Practise this topic