Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. ..srclru.cpp: In instantiation of 'void LRUCache<K, V>::put(K, V) [with K
  2. = int; V = int]':
  3. ..srclru.cpp:70:20: required from here
  4. ..srclru.cpp:57:20: error: request for member 'size' in 'v', which is of
  5. non-class type 'int'
  6. if(capacity == v.size()) { // vector v is full
  7. ~~^~~~
  8.  
  9. template <class K, class V>
  10. class LRUCache {
  11.  
  12. private:
  13. int capacity;
  14. vector<K> v;
  15. unordered_map<K, V> m;
  16. int findIndexOfK(K k);
  17. public:
  18. LRUCache(int vcapacity) : capacity(vcapacity) {
  19.  
  20. }
  21. V get(K k);
  22. void put(K k, V v);
  23. };
  24.  
  25. template <class K, class V>
  26. int LRUCache<K, V>::findIndexOfK(K k) {
  27. int index {-1};
  28. for(int i=0; i < capacity; i++) {
  29. if(v[i]==k) {
  30. index = i;
  31. break;
  32. }
  33. }
  34. return index;
  35. }
  36.  
  37. template <class K, class V>
  38. V LRUCache<K, V>::get(K k) {
  39. auto i = m.find(k);
  40. if(i == m.end()) {
  41. return -1;
  42. }
  43. else
  44. return i->second;
  45. }
  46.  
  47. template <class K, class V>
  48. void LRUCache<K, V>::put(K k, V v) {
  49. int index = findIndexOfK(k);
  50. if(index == -1) {
  51. if(capacity == v.size()) { // vector v is full
  52. v.erase(v.begin()); // Remove the least recent one
  53. }
  54. }
  55. else {
  56. v.erase(v.begin()+index); // Remove the existing one whose index was found
  57. }
  58. m[k] = v;
  59. v.add(k);
  60. }
  61.  
  62. int main() {
  63. LRUCache<int, int> lrucache(3);
  64. lrucache.put(2, 33);
  65. lrucache.put(5, 40);
  66. assert(lrucache.get(2) == 33);
  67. return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement