Bounded LRU cache on std::list plus hash map
C++
#include <list>
#include <unordered_map>
#include <utility>
struct LruCache {
explicit LruCache(std::size_t cap) : cap(cap) {}
int* find(int k) {
auto it = map.find(k);
if (it == map.end()) return nullptr;
order.splice(order.begin(), order, it->second);
return &it->second->second;
}
void put(int k, int v) {
if (int* p = find(k)) { *p = v; return; }
if (map.size() == cap) { map.erase(order.back().first); order.pop_back(); }
order.emplace_front(k, v);
map[k] = order.begin();
}
std::size_t cap;
std::list<std::pair<int, int>> order;
std::unordered_map<int, std::list<std::pair<int, int>>::iterator> map;
};