forked from Sahana-Math/Section-G-SE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lru-cache.cpp
42 lines (40 loc) · 1.28 KB
/
lru-cache.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class LRUCache {
private:
list<pair<int, int>> cache;
int cacheSize;
unordered_map<int, list<pair<int, int>>::iterator> mp;
public:
LRUCache(int capacity) {
cacheSize = capacity;
}
int get(int key) {
// if the key exists
if(mp.find(key) != mp.end()) {
auto it = mp[key];
int val = it -> second;
cache.erase(it); // erase it
cache.push_front({key, val}); // push it to the front as it was recently used
mp[key] = cache.begin(); // make that the front
return val;
}
else return -1;
}
void put(int key, int value) {
// check if the key is new
if(mp.find(key) == mp.end()) {
if(cacheSize == cache.size()) { // check if the cache buffer is full
// remove the least recently used
pair<int, int> lru = cache.back();
cache.pop_back();
mp.erase(lru.first);
}
}
// if the key is present in the cache, erase it.
else {
cache.erase(mp[key]);
}
// as it was recently accessed/used, push it to the front of the cache buffer.
cache.push_front({key, value});
mp[key] = cache.begin();
}
};