<
typenameK,
typenameV>
60template<
typenameK,
typenameV>
66std::unordered_map<K, CacheNode<K, V> *>
91 head->prev = node_ptr;
100 if(
head== node_ptr) {
104CacheNode<K, V> *prev = node_ptr->
prev;
105CacheNode<K, V> *next = node_ptr->
next;
114node_ptr->
prev=
nullptr;
115node_ptr->
next=
nullptr;
133CacheNode<K, V> *temp =
tail;
135 tail->next =
nullptr;
145 void put(K key, V value) {
148 node_map[key]->data.second = value;
160CacheNode<K, V> *newNode =
newCacheNode<K, V>({key, value});
174 throwstd::runtime_error(
"key is not present in the cache");
178V value =
node_map[key]->data.second;
224assert(cache.
size() == 0);
226assert(cache.
empty());
233assert(cache.
size() == 2);
235assert(!cache.
empty());
238assert(cache.
get(1) == 10);
239assert(cache.
get(-2) == 20);
241cache.
put(-3, -30);
247assert(cache.
size() == 5);
249assert(!cache.
empty());
256}
catch(
conststd::runtime_error &e) {
257assert(std::string(e.what()) ==
"key is not present in the cache");
261assert(cache.
get(-2) == 20);
262assert(cache.
get(-3) == -30);
263assert(cache.
get(4) == 40);
264assert(cache.
get(5) == -50);
265assert(cache.
get(6) == 60);
267std::cout <<
"test - passed\n";
Node for a doubly linked list with data, prev and next pointers.
D_Node< T > * next
next node in the doubly linked list
D_Node< T > * prev
previous node in the doubly linked list
CacheNode< K, V > * head
head of the doubly linked list
int size() const
Returns the number of items present in the cache.
void push_front(CacheNode< K, V > *node_ptr)
push the node to the front of the linked list.
CacheNode< K, V > * tail
tail of the doubly linked list
void put(K key, V value)
upsert a key-value pair
~LRUCache()
destructs the cache, iterates on the map and deletes every node present in the cache.
LRUCache(int _capacity)
Constructor, Initialize the head and tail pointers to nullptr and initialize the _capacity of the cac...
std::unordered_map< K, CacheNode< K, V > * > node_map
maps the key to the node address
void pop_back()
pop the last node in the linked list.
bool empty() const
returns whether the cache is empty or not
V get(K key)
get the value of the key-value pair if exists
void make_recent(CacheNode< K, V > *node_ptr)
move the existing node in the list to the beginning of the list.
std::uint32_t _capacity
maximum capacity of the cache
int capacity() const
Returns the total capacity of the cache.
static void test()
self test implementations
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4