C++实现的简单LRU算法
面经复习记录之实现LRU算法
#include<list>
#include<unordered_map>
#include<iostream>
using namespace std;
template<typename T,class M>
class LRUCache {
private:
//使用双向链表存储顺序信息
//hashmap存数据
size_t capacity;
list<pair<T, M>> cache;
unordered_map<T, typename list<pair<T,M>>::iterator> hashmap;
public:
LRUCache(size_t _capacity):capacity(_capacity){}
M get(T key) {
auto it = hashmap.find(key);
if (it != hashmap.end()) {
auto value = *hashmap[key];
//置顶页面
cache.erase(hashmap[key]);
cache.push_front(value);
//更行hash
hashmap[key] = cache.begin();
return value.second;
}
return NULL;
}
void put(T key, M value) {
auto it = hashmap.find(key);
if (it != hashmap.end()) {
cache.erase(hashmap[key]);
}
else if (cache.size() == capacity) {
T k = cache.back().first;
//可能value改变了 所以删除然后重新添加新的kv
hashmap.erase(k);
cache.pop_back();
}
cache.push_front(make_pair(key, value));
hashmap[key] = cache.begin();
}
void showcache() {
for (auto it : cache) {
cout << it.first << " " << it.second << endl;
}
}
};
测试样例
int main() {
LRUCache<int, char> lru(3);
lru.put(2, 'c');
lru.put(3, '4');
lru.put(4, 'j');
lru.showcache();
lru.put(5, '0');
cout << lru.get(2) << endl;
lru.showcache();
cout << lru.get(3) << endl;
lru.showcache();
}