Advertisement
imashutosh51

LRU cache

Jul 31st, 2022
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.08 KB | None | 0 0
  1. /*
  2. Time complexity :complexity of erase only
  3. we created a cache list of pair which will keep key and value pairs and we are keeping address of that pair of cache ie. list in map
  4. whose key will be actual key of that pair.
  5. we will keep our cache as most recent accesed element at front and least recent accessed element at back of cache.
  6. refreshposition will adjust position of an internal node in cache ie. node that is not in front nor in back to front.
  7. */
  8.  
  9. class LRUCache{
  10.     private:
  11.       list<pair<int,int>> cache;
  12.       unordered_map<int,list<pair<int,int>>::iterator> mymap;  //Key, address in cache array ie. our cache memory
  13.       int capacity;
  14.    
  15.     public:
  16.     void refreshPosition(int key,int value){
  17.         cache.erase(mymap[key]);
  18.         cache.push_front(make_pair(key,value));
  19.         mymap[key] = cache.begin();     //Addr of new position stored in map
  20.     }
  21.  
  22.    
  23.     LRUCache(int cap){
  24.        this->capacity = cap;
  25.     }
  26.    
  27.     int get(int key){
  28.         if(mymap.find(key)!=mymap.end()){
  29.             refreshPosition(key,(*mymap[key]).second);  //just because it has been hit,so it's most recently used so updation.here start is used because
  30.                                                         //mymap[key] gives the addresss of that pair,and * at begining means that pair.
  31.             return (*mymap[key]).second;                //returning value for the key
  32.         }
  33.         return -1;
  34.     }
  35.    
  36.     void set(int key, int value){
  37.         if(mymap.find(key)!=mymap.end())
  38.             refreshPosition(key,value);               //if present in the cache,then updating the position to front of the cache
  39.         else{                                         //if not present in cache,then adding it into cache and at the front of the cache
  40.             cache.push_front(make_pair(key,value));
  41.             mymap[key] = cache.begin();
  42.             if(mymap.size()>capacity){                //if capacity exceeds,removing element from the back.
  43.                 mymap.erase(cache.back().first);
  44.                 cache.pop_back();
  45.             }
  46.         }
  47.     }
  48. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement