1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
| #include<iostream> #include <string.h> #include<mutex>
namespace _LRU{
template<typename K, typename V> class Node{ public: K key; V value; Node* prev; Node* next;
Node(K k, V v):key(k),value(v),prev(nullptr),next(nullptr){}
};
template<typename K, typename V> class LRUCache{ public: LRUCache(int cap) : capacity(cap),size(0){ head = new Node<K,V>(K(),V()); tail = new Node<K,V>(K(),V());
head->next = tail; tail->prev = head; hashTable = new NodePointer[capacity](); }
~LRUCache(){ NodePointer cur = head; while(cur){ NodePointer next = cur->next; delete cur; cur = next; } delete []hashTable; }
void put(K key, V value){ std::lock_guard<std::mutex> lock(mutex); unsigned int index = hash(key); if(hashTable[index]){ hashTable[index]->value = value; moveToHead(hashTable[index]); }else{ NodePointer newNode = new Node<K,V>(key,value); hashTable[index] = newNode; moveToHead(newNode); size++; if(size>capacity){ removeLRU(); size--; } } }
V get(K key) { std::lock_guard<std::mutex> lock(mutex); unsigned int index = hash(key);
NodePointer node = hashTable[index]; while (node) { if (node->key == key) { moveToHead(node); return node->value; } node = node->next; } return V(); } private: int capacity; int size; using NodePointer = Node<K,V>*; NodePointer head; NodePointer tail; NodePointer* hashTable; std::mutex mutex; unsigned int hash(K key) { return std::hash<K>{}(key) % capacity; }
void moveToHead(NodePointer node) { if(node->prev){ node->prev->next = node->next; } if(node->next){ node->next->prev = node->prev; } node->next = head->next; head->next->prev = node; node->prev = head; head->next = node; }
void removeLRU(){ NodePointer lru = tail->prev; if(lru == head) return; lru->prev->next = tail; tail->prev = lru->prev;
unsigned int index = hash(lru->key); hashTable[index] = nullptr; delete lru; } };
};
int main(){ _LRU::LRUCache<int, int> cache(3);
cache.put(1, 1); cache.put(2, 2); std::cout << cache.get(1) << std::endl;
cache.put(3, 3); std::cout << cache.get(2) << std::endl;
cache.put(4, 4); std::cout << cache.get(1) << std::endl; std::cout << cache.get(3) << std::endl; std::cout << cache.get(4) << std::endl; std::cout << cache.get(2) << std::endl; cache.put(5, 5); std::cout << cache.get(5) << std::endl; std::cout << cache.get(2) << std::endl; return 0; }
|