最近在看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. checkbox属性checked="checked"已有,但却不显示打勾的解决办法

    2014-02-05 BIWEB开发技巧 9919 在做权限管理的时候,做了一个功能,就是当勾选栏目,把所有的权限全勾上.刚开始使用了如下代码: function check(id,check) { ...

  2. VMWARE里启动kylin16.0时出现'SMBus Host Controller not enabled'(还未进入系统)

    在Vmware里安装完Ubuntu16.10,启动时出现'SMBus Host Controller not enabled'错误提示,进不到图形界面.网上搜了一下,解决办法是在图形界面里进终端窗口, ...

  3. springmvc的foward和redirect跳转简单解析

    Spring MVC 中,我们在返回逻辑视图时,框架会通过 viewResolver 来解析得到具体的 View,然后向浏览器渲染.假设逻辑视图名为 hello,通过配置,我们 配置某个 ViewRe ...

  4. (48) odoo的button用法

    button 应用的比较多,这里来汇总一下 按钮<button>,支持的属性     icon  可用的icon在 addons/web/static/src/img/icons     ...

  5. bean生命周期

    一.Bean的定义Spring通常通过配置文件定义Bean.如:xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:s ...

  6. SAP LOGON DATA CHECK

    之前有朋友做过RFC登录验证,后来群里又有很多人问SAP的登录验证函数. 后来自己找找了,看看了,然后改写了一个LOGON DATA CHECK... FUNCTION ZUSER_CHECK_LOG ...

  7. Web自动化基础(一)使用Selenium定位元素

    什么是元素?我们知道网页上有什么内容显示出来,比如一个按钮,一个输入框,一张图片,都可以理解成元素,这些元素是由html代码构成的,比如图片可以用<img>标签来展示,一个输入框可以用&l ...

  8. tab切换-淘宝案例

    案例: html: <body> <div class="wrap" id="wrap"> <div class="no ...

  9. 转载:手机网页制作的认识(有关meta标签)

    下面是手机网页的一些认识: 一.<meta name="viewport" id="viewport" content="width=devic ...

  10. Mongodb 副本集分片(二)---mongodb副本集部署脚本详解

    分享下,最近做的一主一从一仲裁的示例,如有需要,大家可以扩展成一主两从一仲裁. 大家可以看到  我的集群名字沿用了默认的neunnm,如果是其他的话   大家注意修改. 需要辅助文件hosts.con ...