InvoDB/invodb/models/cache.h
2021-11-03 09:39:13 +08:00

53 lines
1.1 KiB
C++

//
// Created by i on 2021/11/2.
//
#ifndef INVODBCACHEH
#define INVODBCACHEH
#include <list>
#include <map>
template<typename KT, typename VT>
class LRUCache {
public:
LRUCache(int capacity) : capacity(capacity) {}
bool exist(KT const &key) {
return hash.find(key) != hash.end();
}
VT get(KT const &key) {
if (hash.find(key) == hash.end())
throw "cache error";
else {
VT value = hash[key]->second;
ls.erase(hash[key]);
ls.push_front(std::make_pair(key, value));
hash[key] = ls.begin();
return value;
}
}
void put(KT const &key, VT const &value) {
if (hash.find(key) != hash.end()) {
ls.erase(hash[key]);
}
else if (ls.size() >= capacity) {
hash.erase(ls.back().first);
ls.pop_back();
}
ls.push_front(std::make_pair(key, value));
hash[key] = ls.begin();
}
private:
int capacity;
std::list<std::pair<KT, VT>> ls;
std::unordered_map<KT, typename std::list<std::pair<KT, VT>>::iterator> hash;
};
#endif //INVODBCACHEH