最近在看Leveldb源码,里面用到LRU(Least Recently Used)缓存,所以自己动手来实现一下。LRU Cache通常实现方式为Hash Map + Double Linked List,我使用std::map来代替哈希表。
实现代码如下:
#include <iostream> #include <map> #include <assert.h> using namespace std; // define double linked list node template<class K, class V> struct Node{ K key; V value; Node *pre_node; Node *nxt_node; Node() : key(K()), value(V()), pre_node(0), nxt_node(0){} }; // define LRU cache. template<class K, class V> class LRUCache{ public: typedef Node<K, V> CacheNode; typedef map<K, CacheNode*> HashTable; LRUCache(const int size) : capacity(size), count(0), head(0), tail(0){ head = new CacheNode; tail = new CacheNode; head->nxt_node = tail; tail->pre_node = head; } ~LRUCache(){ HashTable::iterator itr = key_node_map.begin(); for (itr; itr != key_node_map.end(); ++itr) delete itr->second; delete head; delete tail; } void put(const K &key, const V &value){ // check if key already exist. HashTable::const_iterator itr = key_node_map.find(key); if (itr == key_node_map.end()){ CacheNode *node = new CacheNode; node->key = key; node->value = value; if (count == capacity) { CacheNode *tail_node = tail->pre_node; extricateTheNode(tail_node); key_node_map.erase(tail_node->key); delete tail_node; count--; } key_node_map[key] = node; count++; moveToHead(node); } else{ itr->second->value = value; extricateTheNode(itr->second); moveToHead(itr->second); } } V get(const K &key){ // check if key already exist. HashTable::const_iterator itr = key_node_map.find(key); if (itr == key_node_map.end()){ return V(); } else{ extricateTheNode(itr->second); moveToHead(itr->second); return itr->second->value; } } void print(){ if (count == 0) cout << "Empty cache." << endl; cout << "Cache information:" << endl; cout << " " << "capacity: " << capacity << endl; cout << " " << "count: " << count << endl; cout << " " << "map size: " << key_node_map.size() << endl; cout << " " << "keys: "; CacheNode *node = head; while (node->nxt_node != tail) { cout << node->nxt_node->key << ","; node = node->nxt_node; } cout << endl; } private: void moveToHead(CacheNode *node){ assert(head); node->pre_node = head; node->nxt_node = head->nxt_node; head->nxt_node->pre_node = node; head->nxt_node = node; } void extricateTheNode(CacheNode *node){ // evict the node from the list. assert(node != head && node != tail); node->pre_node->nxt_node = node->nxt_node; node->nxt_node->pre_node = node->pre_node; } private: int capacity; int count; Node<K, V> *head; Node<K, V> *tail; HashTable key_node_map; }; int main() { LRUCache<int, int> my_cache(4); for (int i = 0; i < 20; ++i) { int key = rand() % 10 + 1; int value = key * 2; cout << "Put[" << key << "," << value << "]>>>" << endl; my_cache.put(key, value); my_cache.print(); } for (int i = 0; i < 20; ++i) { int key = rand() % 10 + 1; int value = my_cache.get(key); cout << "Get value of " << key << ": " << value << ".>>>" << endl; my_cache.print(); } return 0; }
时间: 2024-10-16 04:58:17