Advertisement
Guest User

Untitled

a guest
Jan 24th, 2018
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. #include <deque>
  2. #include <unordered_map>
  3. #include <algorithm>
  4.  
  5. template<typename T1, typename T2>
  6. class LRU {
  7. public:
  8. LRU(size_t num)
  9. : num(num) {
  10. if (num == 0)
  11. throw std::runtime_error("Invalid number of elements in LRU list");
  12. }
  13.  
  14. void Add(const T1& key, const T2& element) {
  15. MoveTop(key, element);
  16. }
  17.  
  18. const T2* Get(const T1& key) {
  19. auto indexIt = index.find(key);
  20. if (indexIt == index.end())
  21. return nullptr;
  22.  
  23. MoveTop(key, indexIt->second->second);
  24. return &elements.back().second;
  25. }
  26.  
  27. private:
  28. void MoveTop(const T1& key, const T2& element) {
  29. auto indexIt = index.find(key);
  30. if (indexIt == index.end()) {
  31. if (elements.size() >= num) {
  32. index.erase(elements.front().first);
  33. elements.pop_front();
  34. }
  35. }
  36. else {
  37. elements.erase(indexIt->second);
  38. }
  39.  
  40. elements.push_back(std::make_pair(key, element));
  41. index[key] = --elements.end();
  42. }
  43.  
  44. private:
  45. size_t num;
  46. using Element = std::pair <T1, T2>;
  47. using Elements = std::list <Element> ;
  48. Elements elements;
  49. std::unordered_map<T1, typename Elements::iterator> index;
  50. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement