File tree 1 file changed +78
-0
lines changed
1 file changed +78
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+
4
+ class LRUCache {
5
+ // store keys of cache
6
+ list<int > dq;
7
+
8
+ // store references of key in cache
9
+ unordered_map<int , list<int >::iterator> ma;
10
+ int csize; // maximum capacity of cache
11
+
12
+ public:
13
+ LRUCache (int );
14
+ void refer (int );
15
+ void display ();
16
+ };
17
+
18
+ // Declare the size
19
+ LRUCache::LRUCache (int n)
20
+ {
21
+ csize = n;
22
+ }
23
+
24
+ // Refers key x with in the LRU cache
25
+ void LRUCache::refer (int x)
26
+ {
27
+ // not present in cache
28
+ if (ma.find (x) == ma.end ()) {
29
+ // cache is full
30
+ if (dq.size () == csize) {
31
+ // delete least recently used element
32
+ int last = dq.back ();
33
+
34
+ // Pops the last elmeent
35
+ dq.pop_back ();
36
+
37
+ // Erase the last
38
+ ma.erase (last);
39
+ }
40
+ }
41
+
42
+ // present in cache
43
+ else
44
+ dq.erase (ma[x]);
45
+
46
+ // update reference
47
+ dq.push_front (x);
48
+ ma[x] = dq.begin ();
49
+ }
50
+
51
+ // Function to display contents of cache
52
+ void LRUCache::display ()
53
+ {
54
+
55
+ // Iterate in the deque and print
56
+ // all the elements in it
57
+ for (auto it = dq.begin (); it != dq.end ();
58
+ it++)
59
+ cout << (*it) << " " ;
60
+
61
+ cout << endl;
62
+ }
63
+
64
+ // Driver Code
65
+ int main ()
66
+ {
67
+ LRUCache ca (4 );
68
+
69
+ ca.refer (1 );
70
+ ca.refer (2 );
71
+ ca.refer (3 );
72
+ ca.refer (1 );
73
+ ca.refer (4 );
74
+ ca.refer (5 );
75
+ ca.display ();
76
+
77
+ return 0 ;
78
+ }
You can’t perform that action at this time.
0 commit comments