• Source
    1. /* We can use stl container list as a double
    2.   ended queue to store the cache keys, with
    3.   the descending time of reference from front
    4.   to back and a set container to check presence
    5.   of a key. But to fetch the address of the key
    6.   in the list using find(), it takes O(N) time.
    7.   This can be optimized by storing a reference
    8.   (iterator) to each key in a hash map. */
    9. #include <bits/stdc++.h>
    10. using namespace std;
    11.  
    12. class LRUCache
    13. {
    14. // store keys of cache
    15. list<int> dq;
    16.  
    17. // store references of key in cache
    18. unordered_map<int, list<int>::iterator> ma;
    19. int csize; //maximum capacity of cache
    20.  
    21. public:
    22. LRUCache(int);
    23. void refer(int);
    24. void display();
    25. };
    26.  
    27. LRUCache::LRUCache(int n)
    28. {
    29. csize = n;
    30. }
    31.  
    32. /* Refers key x with in the LRU cache */
    33. void LRUCache::refer(int x)
    34. {
    35. // not present in cache
    36. if (ma.find(x) == ma.end())
    37. {
    38. // cache is full
    39. if (dq.size() == csize)
    40. {
    41. //delete least recently used element
    42. int last = dq.back();
    43. dq.pop_back();
    44. ma.erase(last);
    45. }
    46. }
    47.  
    48. // present in cache
    49. else
    50. dq.erase(ma[x]);
    51.  
    52. // update reference
    53. dq.push_front(x);
    54. ma[x] = dq.begin();
    55. }
    56.  
    57. // display contents of cache
    58. void LRUCache::display()
    59. {
    60. for (auto it = dq.begin(); it != dq.end();
    61. it++)
    62. cout << (*it) << " ";
    63.  
    64. cout << endl;
    65. }
    66.  
    67. // Driver program to test above functions
    68. int main()
    69. {
    70. LRUCache ca(4);
    71.  
    72. ca.refer(1);
    73. ca.refer(2);
    74. ca.refer(3);
    75. ca.refer(1);
    76. ca.refer(4);
    77. ca.refer(5);
    78. ca.display();
    79.  
    80. return 0;
    81. }