Advertisement
Guest User

Untitled

a guest
Feb 12th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3. #include <map>
  4. class LRUCache{
  5. public:
  6. int max_capacity;
  7. std::map<int,int> mymap;
  8.  
  9. LRUCache(int capacity) {
  10. max_capacity = capacity;
  11. mymap.clear();
  12. }
  13.  
  14. ~LRUCache() {
  15. mymap.clear();
  16. }
  17.  
  18. int get(int key) {
  19. std::map<int,int>::iterator find;
  20.  
  21. find = mymap.find(key);
  22. if(find == mymap.end()){ // check exist
  23. return -1;
  24. }
  25.  
  26. mymap.erase (find);
  27. mymap.insert (std::pair<int,int>(find->first,find->second));
  28.  
  29. return find->second;
  30. }
  31.  
  32. void set(int key, int value) {
  33. mymap.erase (key);
  34. mymap.insert (std::pair<int,int>(key,value));
  35.  
  36. if(mymap.size() > max_capacity){
  37. mymap.erase (mymap.begin());
  38. }
  39. }
  40. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement