146 LRU Cache
class LRUCache {
public:
LRUCache(const size_t capacity) : cap(capacity) {
cache.reserve(capacity);
}
int get(int key)
{
auto found = cache.find(key);
if (found == cache.end())
return -1;
else {
update_LRU_history(found);
return found->second.first;
}
}
void set(int key, int value)
{
auto found = cache.find(key);
if (found != cache.end()) {
update_LRU_history(found);
cache[key] = { { value, LRU_history.begin() } };
return;
}
else if (LRU_history.size() >= cap) {
cache.erase(LRU_history.back());
LRU_history.pop_back();
LRU_history.push_front(key);
cache.insert({key, make_pair(value, LRU_history.begin())});
}
else {
LRU_history.push_front(key);
cache.insert({ key, make_pair(value, LRU_history.begin()) });
}
}
private:
using value_pointer = pair<int, list<int>::iterator>;
unordered_map<int, value_pointer> cache;
list<int> LRU_history;
const size_t cap;
void update_LRU_history(unordered_map<int, value_pointer>::iterator it)
{
LRU_history.erase(it->second.second);
LRU_history.push_front(it->first);
it->second.second = LRU_history.begin();
}
};Last updated