3#ifndef STEP20_LEAST_RECENTLY_USED_HPP
4#define STEP20_LEAST_RECENTLY_USED_HPP
7#include <unordered_map>
14 class Hash = std::hash<Key>,
15 class KeyEqual = std::equal_to<Key>>
16class linked_hash_map {
18 using value_type = std::pair<const Key, T>;
19 using list_type = std::list<value_type>;
20 using iterator =
typename list_type::iterator;
21 linked_hash_map() =
default;
22 linked_hash_map(linked_hash_map&&) =
default;
23 linked_hash_map& operator=(linked_hash_map&&) =
default;
24 linked_hash_map(
const linked_hash_map&) =
delete;
25 linked_hash_map& operator=(
const linked_hash_map&) =
delete;
26 virtual ~linked_hash_map() =
default;
27 auto size()
const {
return list_.size(); }
28 iterator begin() {
return list_.begin(); }
29 iterator end() {
return list_.end(); }
30 void transfer(iterator from, iterator
to) { list_.splice(
to, list_, from); }
32 iterator find(
const Key& key)
34 auto it = map_.find(key);
35 return it == map_.end() ? list_.end() : it->second;
38 iterator erase(iterator it)
40 map_.erase(it->first);
41 return list_.erase(it);
45 std::pair<iterator, bool> emplace(iterator it,
const Key& key, M&& val)
47 if (
auto pos = find(key); pos != end())
49 it = list_.emplace(it, key, std::forward<M>(val));
51 map_.emplace(key, it);
62 std::unordered_map<Key, iterator, Hash, KeyEqual> map_;
70 class Hash = std::hash<Key>,
71 class KeyEqual = std::equal_to<Key>>
73 detail::linked_hash_map<Key, T, Hash, KeyEqual> map_;
74 std::size_t capacity_;
77 explicit cache(std::size_t capacity) : capacity_(capacity) {}
85 const T*
find(
const Key& key)
87 auto it = map_.find(key);
90 map_.transfer(it, map_.end());
91 return std::addressof(it->second);
98 auto [it, success] = map_.emplace(map_.end(), key, val);
100 map_.transfer(it, map_.end());
104 while (map_.size() > capacity_)
105 map_.erase(map_.begin());
An O(1) algorithm for implementing the LRU cache eviction scheme.
Definition least_recently_used.hpp:72
const T * find(const Key &key)
Definition least_recently_used.hpp:85
cache & operator=(cache &&)=default
cache(const cache &)=delete
cache & operator=(const cache &)=delete
void insert_or_assign(const Key &key, const T &val)
Definition least_recently_used.hpp:96
cache(std::size_t capacity)
Definition least_recently_used.hpp:77
Definition least_recently_used.hpp:9
To to(From &&from)
Definition to.hpp:13