LRUCache explanation
LRUCache is a cache system, mainly in the operating system with a lot more, I'm only here to implement a simple method, the principle is correct, but the operating system's internal cache code I have not seen.
LRU is least recently used meaning, the cache everyone knows is the meaning of caching. is to save the most recently used elements in the cache, so that when accessing these elements, the speed will be more quickly accessible.
Cache is usually stored in the key-value pairs, that is, (key, value)
is roughly the simplest of two operations:
- One is
get(key)
that the method is to look for an element from key
the cache, some to return its value
value, and no to return it -1
.
- One is
set(key , value)
, this method is if the cache does not havekey
element, put it in the cache, and if the cache is full, throw away the least common one (key, value) and put the new element in. If the cache already haskey
element, then the updatekey
Ofvalue
Value.
Code implementation
Everyone should understand what the system is, and put my Code implementation below:
main.cpp//lrucache////Created by Alps on 14/12/5.//Copyright (c) 2014 Chen. All rights reserved.//#include <iostream> #include <map>using namespace Std;class lrucache{public:struct No de{int key; int value; Node* Next; node* Pre; Node (int k, int v): Key (k), Value (v), Next (null), pre (NULL) {}}; int maxsize; int cursize; typedef node* Keynode; Map<int,keynode> Cachemap; Keynode Head; Keynode tail; LRUCache (int capacity) {head = new Node ( -1,-1); tail = new Node ( -1,-1); Head->next = tail; Tail->pre = head; MaxSize = capacity; cursize = 0; } void Inserthead (Keynode node) {Node->next = head->next; Node->pre = head; head->next->pre = node; Head->next = node; } void Deletenode (Keynode node) {Node->pre->next = node->next; Node->next->pre = node->pre; } int get (int key) {map<int, keynode>::iterator iter; iter = Cachemap.find (key); if (iter = = Cachemap.end ()) {return-1; }else{Keynode temp = iter->second; Deletenode (temp); Inserthead (temp); Return temp->value; } return-1; } void set (int key, int value) {map<int, keynode>::iterator iter; iter = Cachemap.find (key); if (iter = = Cachemap.end ()) {if (cursize >= maxsize) {Keynode freenode = tail->pre; Cachemap.erase (Freenode->key); Deletenode (freenode); Free (freenode); Keynode temp = (keynode) malloc (sizeof (struct Node)); *temp = Node (Key,value); Inserthead (temp); Cachemap[key] = temp; }else{Keynode temp = (keynode) malloc (sizeof (struct Node)); *temp = Node (key, value); Inserthead (temp); cursize++; Cachemap[key] = temp; }}else{Keynode temp = iter->second; Temp->value = value; Deletenode (temp); Inserthead (temp); }}};int Main (int argc, const char * argv[]) {LRUCache L (2); L.set (2, 1); L.set (2, 2); int v = l.get (2); L.set (1, 1); L.set (4, 1); printf ("%d\n", V); printf ("%d\n", L.get (2)); return 0;}
Algorithmic Learning-LRUCache Learning (c + +)