14#include <unordered_map>
22template <
class Tkey,
class Tdata,
class Thash = std::hash<Tkey>,
class Tequality = std::equal_to<>>
25 using PairType = std::pair<Tkey, Tdata>;
26 using StorageType = std::list<PairType>;
27 using IteratorType = StorageType::iterator;
28 using LookupType = std::unordered_map<Tkey, IteratorType, Thash, Tequality>;
49 return this->lookup.find(key) != this->lookup.end();
57 void Insert(
const Tkey &key, Tdata &&item)
59 auto it = this->lookup.find(key);
60 if (it != this->lookup.end()) {
62 it->second->second = std::move(item);
67 if (this->data.size() >= this->capacity) {
68 this->lookup.erase(
data.back().first);
69 this->data.pop_back();
73 this->data.emplace_front(key, std::move(item));
74 this->lookup.emplace(key, this->data.begin());
57 void Insert(
const Tkey &key, Tdata &&item) {
…}
92 inline const Tdata &
Get(
const Tkey &key)
94 auto it = this->lookup.find(key);
95 if (it == this->lookup.end())
throw std::out_of_range(
"item not found");
97 this->data.splice(this->data.begin(), this->data, it->second);
99 return this->data.front().second;
92 inline const Tdata &
Get(
const Tkey &key) {
…}
110 auto it = this->lookup.find(key);
111 if (it == this->lookup.end())
return nullptr;
114 this->data.splice(this->data.begin(), this->data, it->second);
116 return &this->data.front().second;
Size limited cache with a least recently used eviction strategy.
const size_t capacity
Number of items to cache.
StorageType data
Ordered list of all items.
Tdata * GetIfValid(const auto &key)
Get an item from the cache.
LRUCache(size_t max_items)
Construct new LRU cache map.
void Insert(const Tkey &key, Tdata &&item)
Insert a new data item with a specified key.
void Clear()
Clear the cache.
LookupType lookup
Map of keys to items.
const Tdata & Get(const Tkey &key)
Get an item from the cache.
bool Contains(const Tkey &key)
Test if a key is already contained in the cache.