最近在看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;
}

LRU Cache实现的更多相关文章

  1. [LeetCode] LRU Cache 最近最少使用页面置换缓存器

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...

  2. 【leetcode】LRU Cache

    题目简述: Design and implement a data structure for Least Recently Used (LRU) cache. It should support t ...

  3. LeetCode:LRU Cache

    题目大意:设计一个用于LRU cache算法的数据结构. 题目链接.关于LRU的基本知识可参考here 分析:为了保持cache的性能,使查找,插入,删除都有较高的性能,我们使用双向链表(std::l ...

  4. 【leetcode】LRU Cache(hard)★

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...

  5. [LintCode] LRU Cache 缓存器

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...

  6. LRU Cache [LeetCode]

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...

  7. 43. Merge Sorted Array && LRU Cache

    Merge Sorted Array OJ: https://oj.leetcode.com/problems/merge-sorted-array/ Given two sorted integer ...

  8. LeetCode——LRU Cache

    Description: Design and implement a data structure for Least Recently Used (LRU) cache. It should su ...

  9. LRU Cache

    LRU Cache 题目链接:https://oj.leetcode.com/problems/lru-cache/ Design and implement a data structure for ...

随机推荐

  1. Node 编程规范

    空格, 2个, 因为有多层函数嵌套 行宽, 80个字符 语句分隔, 一律用; 并且占一行 变量定义, 每一个都要用 var, 并且不要定义全局变量 变量名和属性名, 小驼峰, yourName 函数, ...

  2. 零配置文件搭建SpringMVC实践纪录

    本篇记录使用纯java代码搭建SpringMVC工程的实践,只是一个demo.再开始之前先热身下,给出SpringMVC调用流程图,讲解的是一个http request请求到达SpringMVC框架后 ...

  3. centos 忘记密码

    装了个  centos 6.8  安装的时候 要输入 新用户和密码 用 新的用户密码 进去后 各种没权限  重新修改 root 密码   一切OK 步骤 1.重新启动Centos,在启动过程中,长按“ ...

  4. MySQL学习记录--生成时间日期数据

    时间数据格式组件: 组件 定义 范围 YYYY 年份,包括世纪 1000~9999 MM 月份 01(January)~12(December) DD 日 01~31 HH 小时 00~23 HHH ...

  5. Mac下python初学之Image库(PIL)

    Mac下python 使用Image库 安装PIL,下载http://www.pythonware.com/products/pil/ 解压PIL源码包,阅读README知道需要使用python se ...

  6. 通过图片对比带给你不一样的KMP算法体验

    KMP 算法,俗称“看毛片”算法,是字符串匹配中的很强大的一个算法,不过,对于初学者来说,要弄懂它确实不易. 笔者认为,KMP 算法之所以难懂,很大一部分原因是很多实现的方法在一些细节的差异.体现在几 ...

  7. Scala学习 —— 元组&映射

    再说集合之前,我们先来回顾一下映射&元祖 映射是键/值对偶的集合,Scala有一个通用的叫法--元组,也就是n个对象的聚集,并不一定要相同类型的.对偶不过是一个n=2的元祖.元祖对于那种需要将 ...

  8. SpringMVC流程

    Spring工作流程描述 1. 用户向服务器发送请求,请求被Spring 前端控制Servelt DispatcherServlet捕获: 2. DispatcherServlet对请求URL进行解析 ...

  9. C++语法-指针 (1)

    <C++程序设计> 谭浩强  清华大学出版社 2016-08-03 1.P167 一般的C++编译系统为每个指针变量分配4个字节的存储单元,用来存放变量的地址. 2.P169 .cpp文件 ...

  10. JavaScript引擎LHS查找和RHS查找

    要想真正理解Javascript脚本中每一句代码的执行过程,需要弄清楚几个基本概念:1.引擎,从头到尾负责整个 JavaScript 程序的编译及执行过程.2.编译器,引擎的好朋友之一,负责语法分析及 ...