-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathlru-cache.cc
More file actions
37 lines (34 loc) · 713 Bytes
/
Copy pathlru-cache.cc
File metadata and controls
37 lines (34 loc) · 713 Bytes
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
// LRU Cache
class LRUCache {
public:
LRUCache(int capacity) : c(capacity) {}
void touch(int key) {
pair<int, int> x = *s[key];
a.erase(s[key]);
a.push_front(x);
s[x.first] = a.begin();
}
int get(int key) {
if (! s.count(key))
return -1;
touch(key);
return a.begin()->second;
}
void set(int key, int value) {
if (s.count(key)) {
touch(key);
a.begin()->second = value;
} else {
if (s.size() >= c) {
s.erase(a.rbegin()->first);
a.pop_back();
}
a.push_front(make_pair(key, value));
s[key] = a.begin();
}
}
private:
map<int, list<pair<int, int> >::iterator> s;
list<pair<int, int> > a;
int c;
};