1#ifndef LRU_CACHE_HPP_CII58WXX
2#define LRU_CACHE_HPP_CII58WXX
7#include <unordered_map>
22template<
typename KEY,
typename VALUE,
typename GENERATOR = std::function<VALUE(const KEY&)>>
26 using generator = GENERATOR;
28 using value_type = VALUE;
51 auto found = m_cache.find(key);
52 if (found == m_cache.end()) {
55 return refresh(found);
60 using list_type = std::list<key_type>;
61 using entry_type = std::pair<value_type, typename list_type::iterator>;
62 using map_type = std::unordered_map<key_type, entry_type>;
64 value_type& add(
const key_type& k)
66 if (m_cache.size() >= m_capacity) {
70 m_index.emplace_front(k);
71 entry_type entry = std::make_pair(m_generator(k), m_index.begin());
72 auto insertion = m_cache.insert(std::make_pair(k, std::move(entry)));
73 assert(insertion.second ==
true);
74 return insertion.first->second.first;
77 value_type& refresh(
typename map_type::iterator found)
79 m_index.splice(m_index.begin(), m_index, found->second.second);
80 assert(m_index.begin() == found->second.second);
81 return found->second.first;
86 if (!m_index.empty()) {
87 m_cache.erase(m_index.back());
92 generator m_generator;
93 std::size_t m_capacity;
Least-Recently-Used cache.
value_type & operator[](const key_type &key)
Access a cache entry.
LruCache(generator g, std::size_t capacity)