8#include <unordered_map>
28template <
typename K,
typename V>
41 std::optional<std::reference_wrapper<V>>
get(
const K& key) {
42 const auto it = map.find(key);
47 const auto store_entry_itr = it->second;
48 return store_entry_itr->second;
59 void put(
const K& key,
const V& value) {
60 const auto it = map.find(key);
61 if (it != map.end()) {
62 auto store_entry_itr = it->second;
63 store_entry_itr->second = value;
66 if (capacity == store.size()) {
67 map.erase(store.back().first);
70 store.emplace_front(std::pair{key, value});
71 map[key] = store.begin();
81 bool exists(
const K& key)
const {
return map.find(key) != map.end(); }
89 const auto it = map.find(key);
92 store.erase(it->second);
98 size_t size()
const {
return store.size(); }
102 std::list<std::pair<K, V>> store;
103 std::unordered_map<K, typename std::list<std::pair<K, V>>::iterator> map;
107 void setMRU(
const K& key) {
108 auto element_itr = map[key];
109 store.splice(store.begin(), store, element_itr);
A Least Recently Used (LRU) cache with O(1) access and eviction.
std::optional< std::reference_wrapper< V > > get(const K &key)
Retrieves a value from the cache.
bool exists(const K &key) const
Checks if a key exists in the cache.
void put(const K &key, const V &value)
Inserts or updates a key-value pair in the cache.
LRU(size_t size)
Constructs an LRU cache with the specified capacity.
size_t size() const
Returns the current number of entries in the cache.
void remove(const K &key)
Removes a key-value pair from the cache.