Show contents
Chapter 6 of 7 · 25 min
Final project: a generic LRU cache
By the end of this chapter, you'll be able to
- Design a class template constrained by a concept
- Combine std::list and std::unordered_map for O(1) operations
- Return an optional value with std::optional
- Explain why std::list iterators stay valid
Step 1: the design
Two structures work together:
- a
std::listof(key, value)pairs, ordered from most recently used (front) to least recently used (back); - a
std::unordered_mapthat associates each key with an iterator to its place in the list, to find it in O(1).
On each successful read, the element is moved to the front of the list with splice, with no copy or reallocation. When the cache is full, the last element is removed. Every operation is constant time.
Oslo is stored at the front. Each operation cost O(1).
Text description of the animation
- Two cities requested: two slow calls, stored in the cache.
- The most recent is at the front.
- Dakar is requested again: the map directly gives its place in the list.
- splice moves it back to the front, with no copy.
- The cache is full: the last element, the least recently used, is removed.
- Oslo is stored at the front. Each operation cost O(1).
Step 2: the program
#include <concepts>
#include <cstddef>
#include <functional>
#include <iostream>
#include <list>
#include <optional>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
template <typename K>
concept Hashable = requires(const K& k) {
{ std::hash<K>{}(k) } -> std::convertible_to<std::size_t>;
};
template <Hashable K, typename V>
class LruCache {
public:
explicit LruCache(std::size_t capacity) : capacity_(capacity) {}
std::optional<V> get(const K& key) {
auto it = index_.find(key);
if (it == index_.end()) {
++misses_;
return std::nullopt;
}
order_.splice(order_.begin(), order_, it->second); // becomes the most recent
++hits_;
return it->second->second;
}
void put(const K& key, V value) {
auto it = index_.find(key);
if (it != index_.end()) {
it->second->second = std::move(value);
order_.splice(order_.begin(), order_, it->second);
return;
}
if (order_.size() == capacity_) {
index_.erase(order_.back().first); // evicts the least recently used
order_.pop_back();
}
order_.emplace_front(key, std::move(value));
index_[key] = order_.begin();
}
std::vector<K> keys() const {
std::vector<K> result;
for (const auto& entry : order_) result.push_back(entry.first);
return result;
}
std::size_t hits() const { return hits_; }
std::size_t misses() const { return misses_; }
private:
std::size_t capacity_;
std::list<std::pair<K, V>> order_;
std::unordered_map<K, typename std::list<std::pair<K, V>>::iterator> index_;
std::size_t hits_ = 0;
std::size_t misses_ = 0;
};
int slow_calls = 0;
std::string slow_weather(const std::string& city) {
++slow_calls; // imagine a second of network wait here
return city + ": " + std::to_string(20 + static_cast<int>(city.size())) + " °C";
}
std::string weather(LruCache<std::string, std::string>& cache, const std::string& city) {
if (auto r = cache.get(city)) return *r;
std::string value = slow_weather(city);
cache.put(city, value);
return value;
}
int main() {
LruCache<std::string, std::string> cache(2);
for (const char* city : {"Dakar", "Lima", "Dakar", "Oslo", "Lima", "Dakar"}) {
std::cout << weather(cache, city) << '\n';
}
const char* separator = "order: ";
for (const auto& key : cache.keys()) {
std::cout << separator << key;
separator = ", ";
}
std::cout << "\nhits " << cache.hits() << ", misses " << cache.misses() << ", slow calls " << slow_calls << '\n';
}
Dakar: 25 °C
Lima: 24 °C
Dakar: 25 °C
Oslo: 24 °C
Lima: 24 °C
Dakar: 25 °C
order: Dakar, Lima
hits 1, misses 5, slow calls 5
The choices that matter:
- The
Hashableconcept requires thatstd::hash<K>exists, which theunordered_mapneeds. With a key type that doesn't allow it, the error appears where the cache is declared, naming the concept. std::optional<V>expresses "maybe a value":std::nullopton a miss.if (auto r = cache.get(city))tests for presence and gives access to the value with*r.splicemoves a node of a list (here, from one place to another in the same list) by only adjusting pointers.typename std::list<…>::iterator: the wordtypenametells the compiler that this name, which depends on a template parameter, refers to a type.- With a capacity of 2 and this sequence of requests, the cache only avoids one slow call: choosing the capacity matters as much as the algorithm. With a capacity of 3, it would avoid three.
Your turn
Worked exercise
Worked exercise: removing an entry
Add to the cache a method bool remove(const K& key) that deletes the entry if it exists (returns true), without touching the order of the others. Test it with a cache from integers to strings: fill it with 1, 2, 3, remove 2, and check that the remaining keys are in the right order and that removing 2 a second time returns false.
Hint 1
index_.find(key), then erase the element from the list with order_.erase(it->second) before erasing the map's entry.Hint 2
it can no longer be used.Show the solution and common mistakes
#include <cstddef>
#include <iostream>
#include <list>
#include <string>
#include <unordered_map>
#include <utility>
template <typename K, typename V>
class LruCache {
public:
explicit LruCache(std::size_t capacity) : capacity_(capacity) {}
void put(const K& key, V 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() == capacity_) {
index_.erase(order_.back().first);
order_.pop_back();
}
order_.emplace_front(key, std::move(value));
index_[key] = order_.begin();
}
bool remove(const K& key) {
auto it = index_.find(key);
if (it == index_.end()) return false;
order_.erase(it->second);
index_.erase(it);
return true;
}
const std::list<std::pair<K, V>>& content() const { return order_; }
private:
std::size_t capacity_;
std::list<std::pair<K, V>> order_;
std::unordered_map<K, typename std::list<std::pair<K, V>>::iterator> index_;
};
int main() {
LruCache<int, std::string> cache(3);
cache.put(1, "one");
cache.put(2, "two");
cache.put(3, "three");
std::cout << std::boolalpha << cache.remove(2) << ' ' << cache.remove(2) << '\n';
for (const auto& [key, value] : cache.content()) {
std::cout << key << " = " << value << '\n';
}
}
true false
3 = three
1 = one
if (auto it = …; it != index_.end()) declares it inside the if: the variable only exists where it's needed.
Common mistakes:
- Erasing the map's entry first, then using
it->second:itrefers to a destroyed element, that's a use after free. - Forgetting to erase the map's entry: it keeps an iterator to a deleted node, and the next read of that key reads freed memory.
Summary
- 1An LRU cache combines a list (the usage order) and a table (direct access): everything is O(1).
- 2A concept documents and checks what a template requires of its types.
- 3std::optional expresses a value that may be missing, with no pointer or special value.
- 4splice moves a list node without copying; list iterators stay valid.
- 5A vector's iterators are invalidated when it reorganises: never store them.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.