skip to content

In C++, why does an LRU cache pair std::list with an unordered_map of list iterators, and what does list::splice guarantee that makes it work?

level: seniorimportance: should knowfreq 50%

answer

  1. recency order plus key lookup
  2. an iterator that never goes stale
  3. relink, do not copy
  4. range splice from another list

basics

~20 s

The list holds entries in recency order; the hash map finds each entry's node by key. list::splice moves a node to the front in constant time, without copying or throwing, and its iterator stays valid, so the map needs no update.

solid answer

~50 s

An LRU cache needs two things at once: lookup by key and an order of use that can be updated cheaply. `std::unordered_map<Key, std::list<Entry>::iterator>` gives the lookup, and `std::list<Entry>` gives the order, most recent at the front. On a hit, `order.splice(order.begin(), order, it)` relinks that one node to the front. The standard says this overload is constant time, throws nothing, and leaves iterators, pointers and references to the moved element valid, so the iterator stored in the map is still correct. Other list insertions and erasures do not invalidate it either, so the only map edits are adding new keys and erasing evicted ones. Eviction takes `order.back()`, erases its key from the map (which is why the node stores the key), then `pop_back()`. Two edges: splicing a range from a different list is linear, because `size()` must stay constant time, and splicing between lists with unequal allocators is undefined behaviour.

code

cpp · 47 lines
cpp
#include <cstdio>
#include <list>
#include <optional>
#include <string>
#include <unordered_map>
#include <utility>

class LruCache {
public:
    explicit LruCache(std::size_t cap) : cap_(cap) {}

    std::optional<std::string> get(int key) {
        auto it = index_.find(key);
        if (it == index_.end()) return std::nullopt;
        order_.splice(order_.begin(), order_, it->second);  // O(1), no copy, iterator stays valid
        return it->second->second;
    }

    void put(int key, std::string value) {
        if (auto it = index_.find(key); it != index_.end()) {
            it->second->second = std::move(value);
            order_.splice(order_.begin(), order_, it->second);
            return;
        }
        if (order_.size() == cap_) {                          // size() is O(1) since C++11
            index_.erase(order_.back().first);
            order_.pop_back();
        }
        order_.emplace_front(key, std::move(value));
        index_[key] = order_.begin();
    }

private:
    std::size_t cap_;
    std::list<std::pair<int, std::string>> order_;            // front = most recently used
    std::unordered_map<int, std::list<std::pair<int, std::string>>::iterator> index_;
};

int main() {
    LruCache cache(2);
    cache.put(1, "one");
    cache.put(2, "two");
    cache.get(1);              // 1 becomes most recent
    cache.put(3, "three");     // evicts 2
    std::printf("2 cached: %s, 1 cached: %s\n",
                cache.get(2) ? "yes" : "no", cache.get(1) ? "yes" : "no");
}

go deeper

for a junior

Know that a list gives order and a hash map gives lookup, and that splice moves a node without copying it.

for a middle

Walk through get and put with splice, and explain why the stored list iterator stays valid and why each node keeps its key.

for a senior

Cite the splice guarantees and their limits: constant time for one element, linear for a range from another list, undefined behaviour with unequal allocators, and get mutating shared state.

for a principal

Judge when a linked-list LRU is worth its per-node allocations versus approximate schemes such as sampled eviction, given memory, latency and concurrency targets.

## The two structures and their jobs A least-recently-used cache must answer "is key k cached?" in about constant time, and must find and evict the least recently used entry when it is full. No single standard container does both, so the classic design combines two: - a **`std::list<std::pair<Key, Value>>`** holding the entries in order of use, most recent at the front; - a **`std::unordered_map<Key, std::list<...>::iterator>`** mapping each key to its node in that list. The map answers lookups; the list answers "which entry is oldest?" with `back()`. The design only works because a list iterator stays valid for as long as its element exists, whatever happens elsewhere in the list. ## What splice guarantees `std::list` provides three `splice` overloads, each with an lvalue and an rvalue form for the source list: | Call | Effect | Complexity | |---|---|---| | `splice(pos, x)` | moves all of `x` before `pos` | constant | | `splice(pos, x, i)` | moves the element at `i` before `pos` | constant | | `splice(pos, x, first, last)` | moves `[first, last)` before `pos` | constant if `x` is this list; otherwise linear | For every overload, the draft says the elements are moved **destructively** from `x`, nothing is thrown, and pointers, references and iterators to the moved elements keep referring to the same elements, now as members of the destination list. No element is copied, moved-constructed or reallocated; only links change. The linear case exists because `size()` must be constant time since C++11: moving a range from another list must count the moved nodes to update both sizes. Splicing within one list does not change its size, so it stays constant. One precondition is easy to miss: splicing between lists whose allocators compare unequal is **undefined behaviour**, because the nodes were allocated by one allocator and would be freed by the other. ## The cache operations step by step 1. **get(key)**: look the key up in the map. On a miss, return nothing. On a hit, call `order.splice(order.begin(), order, it->second)` to move the node to the front, and return its value. The map entry needs no update. 2. **put(key, value)** on an existing key: update the value through the stored iterator and splice the node to the front. 3. **put(key, value)** on a new key when full: read `order.back().first`, erase that key from the map, then `order.pop_back()`. This is why each node stores its key: the list must be able to tell the map what to erase. 4. **put** then inserts the new entry with `order.emplace_front(key, value)` and stores `order.begin()` in the map. Each operation is constant time on average, dominated by the hash lookup. ## Pitfalls seen in production code - **Storing element pointers or indices instead of iterators.** Pointers would survive splicing, but you cannot splice from a pointer; indices are meaningless in a list. - **Using a vector or deque for the recency order.** Moving an entry to the front would shift elements and invalidate the stored positions. - **Treating `get` as a read.** `get` reorders the list, so a cache shared between threads needs exclusive locking on hits as well as misses; a reader-writer lock that lets readers run concurrently corrupts the list. - **Forgetting the key in the node.** Eviction then needs a linear search of the map. ## Sizing and variations - **Allocation per entry**: every new key costs one list node and one hash-map node. Reserving the map's buckets for the cache capacity up front avoids rehashing during warm-up; rehashing invalidates the map's own iterators, but not the list iterators stored as its values. - **Updates in place**: a hit splices, and an overwrite assigns through the stored iterator, so neither allocates. - **Two-segment designs**: a segmented LRU keeps a probationary list and a protected list and promotes an entry from one to the other with the single-element `splice`, which stays constant time even between two different `std::list` objects with equal allocators. - **Batch eviction**: dropping the oldest k entries at once is a loop of `pop_back`, one map erase per entry. ## The forward_list variant `std::forward_list` offers `splice_after`, but because a node knows only its successor, moving an element requires the iterator **before** it, and splicing a whole list is linear in that list's length (the last node has to be found). That makes it a poor fit for an LRU cache, where the map would have to store predecessor iterators that change whenever a neighbour moves.

  • Why is splicing a range from another std::list linear, when splicing a single element is constant?
    Since C++11, `std::list::size()` must be constant time, so both lists store their element counts. Moving one element changes each count by one. Moving an arbitrary range from another list means counting how many nodes it contains, which is a walk of the range. Splicing a range within the same list leaves its size unchanged, so the standard keeps that case constant.
  • How would you make this LRU cache safe to call from several threads?
    Guard the map and the list together with one `std::mutex` and take it for every operation, including `get`, because a hit splices the node and mutates the list. A shared-read lock is wrong here. Under contention, shard the cache by key hash into several independently locked caches, accepting that recency becomes per shard.

  • list::splice copies the element into the destination list
  • After splice, the iterator stored in the map must be refreshed
  • Splicing any range between two lists is always constant time
  • get() only reads, so concurrent readers need no exclusive lock
  • A std::vector works just as well as the recency list