Skip to content
C++ project #21Advanced

Generic LRU Cache

A header-only LruCache<K, V> template with O(1) get/put/evict using std::list::splice and an unordered_map of iterators, plus a hit-rate simulator.

Estimated time
~6 hours to build
Files
6 files · 392 lines
Technologies
C++17, <list>, <unordered_map>, <optional>, <functional>, Header-only template

Introduction

Caches are everywhere — CPUs, browsers, databases — and least-recently-used eviction is the classic policy. The trick to making every operation constant time is combining two containers: a linked list in recency order and a hash map from key to list node. This project packages that as a reusable class template and measures how capacity affects hit rate.

Problem statement

Implement a generic LRU cache with get (counts hits and misses and marks the key as recent), peek (no side effects), put (insert or update, evicting the least recently used entry when full), erase, resize (evicting as needed), iteration in recency order, statistics and an optional eviction callback. Provide an interactive demo and a simulate command that replays the same key sequence through caches of several capacities.

Objectives

  • Write a class template with a defaulted hash parameter
  • Combine std::list and std::unordered_map for O(1) operations
  • Use std::list::splice to move nodes without invalidating iterators
  • Return optional results and accept callbacks with std::function

Features

  • O(1) get, put, erase and eviction
  • Hits, misses, evictions and hit-rate statistics
  • Eviction callback (used to log evictions)
  • Simulation comparing capacities on one access pattern

Concepts demonstrated

  • Class templates
  • Iterator stability
  • Hash maps
  • Caching policies
  • std::optional
  • Callbacks

System architecture

LruCache stores std::list<std::pair<K, V>> order_ (front = most recent) and std::unordered_map<K, list::iterator> index_. get finds the iterator, splices that node to the front and returns a copy of the value. put updates in place or emplaces at the front, first evicting order_.back() if full. Because list iterators remain valid when other nodes move, the index never needs fixing up. The demo uses LruCache<std::string, std::string>; the simulator instantiates LruCache<int, long long> in front of a deliberately 'slow' function and counts how often it had to be called.

TextArchitecture diagram
index_ (unordered_map) order_ (list, MRU -> LRU)
"home" ----------------------> [home] <-> [blog] <-> [shop]
"blog" ----------------------------------^ ^
"shop" -------------------------------------------------+
get("shop"): splice node to front -> [shop] <-> [home] <-> [blog]

Folder structure

TextProject tree
lru-cache/
├── README.md
├── Makefile
├── src/lru_cache.h
├── src/main.cpp
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

Makefile

20 lines
MakefileMakefile
# Generated for KENHOLT Skills. Usage: make | make test | make clean
CXX = g++
CXXFLAGS = -std=c++17 -Wall -Wextra -O2
SRC := $(wildcard src/*.cpp)
HDR := $(wildcard src/*.h src/*.hpp)
ARGS := $(shell cat tests/args.txt 2>/dev/null)
INPUT := $(wildcard tests/sample-input.txt)
app: $(SRC) $(HDR)
$(CXX) $(CXXFLAGS) -Isrc $(SRC) -o app
test: app
./app $(ARGS) $(if $(INPUT),< $(INPUT),) > actual.txt
diff actual.txt tests/expected-output.txt && echo "Test passed: output matches tests/expected-output.txt"
clean:
rm -f app app.exe actual.txt
.PHONY: test clean

What each file does

src/lru_cache.h
The complete LruCache<Key, Value, Hash> class template.
src/main.cpp
Interactive commands and the capacity simulation using a second instantiation of the template.
Makefile
Build automation: make builds ./app, make test runs the sample session and compares it with the expected output, make clean removes build files.

How to run it

Build

Terminal
g++ -std=c++17 -Wall -Wextra -Isrc src/*.cpp -o app
# or simply: make

Run

Terminal
./app # Linux / macOS
.\app.exe # Windows

Test against the expected output

Terminal
./app < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt # no output means they match
# Windows PowerShell:
# Get-Content tests\sample-input.txt | .\app.exe > actual.txt
# Compare-Object (Get-Content actual.txt) (Get-Content tests\expected-output.txt)

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
> [1/3] MRU -> home=/index.html <- LRU
> [2/3] MRU -> about=/about.html -> home=/index.html <- LRU
> [3/3] MRU -> blog=/blog.html -> about=/about.html -> home=/index.html <- LRU
> hit: home=/index.html
[3/3] MRU -> home=/index.html -> blog=/blog.html -> about=/about.html <- LRU
> evicted about=/about.html
[3/3] MRU -> shop=/shop.html -> home=/index.html -> blog=/blog.html <- LRU
> miss: about
[3/3] MRU -> shop=/shop.html -> home=/index.html -> blog=/blog.html <- LRU
> blog=/blog.html (recency unchanged)
> hit: blog=/blog.html
[3/3] MRU -> blog=/blog.html -> shop=/shop.html -> home=/index.html <- LRU
> [3/3] MRU -> home=/index-v2.html -> blog=/blog.html -> shop=/shop.html <- LRU
> evicted shop=/shop.html
[3/3] MRU -> faq=/faq.html -> home=/index-v2.html -> blog=/blog.html <- LRU
> removed blog
> not cached: shop
> evicted home=/index-v2.html
[1/1] MRU -> faq=/faq.html <- LRU
> error: capacity must be at least 1
> error: usage: put <key> <value>
> hits 2, misses 1, evictions 3, hit rate 66.7%
> 14 requests, 5 distinct keys
capacity 1: 0 hits, 14 loads, 13 evictions, hit rate 0.0%
capacity 2: 0 hits, 14 loads, 12 evictions, hit rate 0.0%
capacity 3: 6 hits, 8 loads, 5 evictions, hit rate 42.9%
capacity 4: 6 hits, 8 loads, 4 evictions, hit rate 42.9%
>
Input
put home /index.html
put about /about.html
put blog /blog.html
get home
put shop /shop.html
get about
peek blog
get blog
put home /index-v2.html
put faq /faq.html
del blog
del shop
resize 1
resize 0
put
stats
simulate 1 2 3 4 : 1 2 3 1 2 4 1 2 5 1 2 3 4 5
quit

Testing

  • Compare ./app < tests/sample-input.txt with tests/expected-output.txt.
  • After get home, adding shop evicts about, not home.
  • peek blog doesn't change the order; get blog moves it to the front.
  • Resizing to 1 evicts from the LRU end; resizing to 0 is rejected.
  • In the simulation, capacities 1 and 2 never hit while 3 reaches 42.9%.

Common errors

Crash after erasing from the list

Remove the key from the index before (or right after) erasing its list node, so you never dereference a dangling iterator.

Template errors mentioning std::hash

Your key type has no std::hash specialisation; pass a custom Hash as the third template argument.

Possible improvements

  • Add time-to-live expiry per entry
  • Make it thread-safe with std::mutex
  • Implement LFU (least frequently used) and compare

Additional challenges

  1. 1Prove each operation is O(1) average.
  2. 2Add get_or_load(key, loader) that calls the loader on a miss.
  3. 3Implement a 2Q or ARC policy and compare hit rates.

Built and tested it yourself? Mark it to update your dashboard.