#pragma once
#include <list>
#include <unordered_map>
template<typename K, typename V>
class LRUCache
{
public:
LRUCache(size_t _capcity):capcity(_capcity)
{
}
~LRUCache()
{
}
void put(K key ,V value)
{
if (dic.count(key))
{
auto it = dic[key];
*it = { key, value };
data.splice(data.begin(), data, it);
}
else
{
data.push_front({ key, value });
dic[key] = data.begin();
}
while (data.size() > capcity)
{
dic.erase(data.back().first);
data.pop_back();
}
}
V get(K key)
{
if (!dic.count(key)) return -1;
auto it = dic[key];
data.splice(data.begin(), data, it);
return it->second;
}
private:
size_t capcity;
std::list<std::pair<K, V>> data;
std::unordered_map<K, typename std::list<std::pair<K, V>>::iterator> dic;
};
使用模板类实现的LRU算法