-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.cpp
More file actions
74 lines (58 loc) · 1.4 KB
/
Copy pathLRUCache.cpp
File metadata and controls
74 lines (58 loc) · 1.4 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
Based on the implementation found here:
https://www.geeksforgeeks.org/lru-cache-implementation/
*/
#include <iostream>
#include <list>
#include <unordered_map>
using std::cout;
using std::list;
using std::unordered_map;
class LRUCache {
list<int> keysList;
unordered_map<int, list<int>::iterator> umap;
int szcache;
public:
LRUCache(int);
void refer(int);
void display();
};
// Constructor
LRUCache::LRUCache(int n) {
szcache = n;
}
// Refer key x within the LRU cache
void LRUCache::refer(int x) {
if (umap.find(x) == umap.end()) { // if key not in cache
cout << x << " : miss\n";
if (keysList.size() == szcache) { // if cache is full
int last = keysList.back(); // copy the last element
keysList.pop_back(); // remove the last element from the list
umap.erase(last); // removes the last element from mapping
}
}
else { // key is in cache
cout << x << " : hit\n";
keysList.erase(umap[x]);
}
// update the reference
keysList.push_front(x);
umap[x] = keysList.begin();
}
// Display the contents of the cache
void LRUCache::display() {
for (auto& e: keysList)
cout << e << " ";
cout << "\n";
}
int main()
{
LRUCache lruc(4);
lruc.refer(1);
lruc.refer(2);
lruc.refer(3);
lruc.refer(1);
lruc.refer(4);
lruc.refer(5);
lruc.display();
}