LRU是Least Recently Used的缩写,意思是最近最少使用,它是一种Cache替换算法。

  实现思路: hashtable + 双向链表

  时间复杂度: 插入,查找,删除:O(1)

  空间使用情况: O(N) :一个链表存储K个数据(stl的hash_map实际占的空间比较大)。

  运行环境:

  linux:redhat , fedora ,centos等(理论上ubuntu , debian,mac os等也可以运行)

  代码:

  [cpp] view plaincopy

  #ifndef __LRUCACHE_H__

  #define __LRUCACHE_H__

  #include

  #include

  #include

  #include

  using namespace __gnu_cxx;

  template

  struct Node{

  K key;

  D data;

  Node *prev, *next;

  };

  template

  class LRUCache{

  public:

  LRUCache(size_t size , bool is_pthread_safe = false){

  if(size <= 0)

  size = 1024;

  pthread_safe = is_pthread_safe;

  if(pthread_safe)

  pthread_mutex_init(&cached_mutex , NULL);

  entries = new Node[size];

  for(size_t i = 0; i < size; ++i)

  cached_entries.push_back(entries + i);

  head = new Node;

  tail = new Node;

  head->prev = NULL;

  head->next = tail;

  tail->prev = head;

  tail->next = NULL;

  }

  ~LRUCache(){

  if(pthread_safe)

  pthread_mutex_destroy(&cached_mutex);

  delete head;

  delete tail;

  delete[] entries;

  }

  void Put(K key, D data);

  D Get(K key);

  private:

  void cached_lock(void){

  if(pthread_safe)

  pthread_mutex_lock(&cached_mutex);

  }

  void cached_unlock(void){

  if(pthread_safe)

  pthread_mutex_unlock(&cached_mutex);

  }

  void detach(Node* node){

  node->prev->next = node->next;

  node->next->prev = node->prev;

  }

  void attach(Node* node){

  node->prev = head;

  node->next = head->next;

  head->next = node;

  node->next->prev = node;

  }

  private:

  hash_map* > cached_map;

  vector* > cached_entries;

  Node * head, *tail;

  Node * entries;

  bool pthread_safe;

  pthread_mutex_t cached_mutex;

  };

  template

  void LRUCache::Put(K key , D data){

  cached_lock();

  Node *node = cached_map[key];

  if(node){

  detach(node);

  node->data = data;

  attach(node);

  }

  else{

  if(cached_entries.empty()){

  node = tail->prev;

  detach(node);

  cached_map.erase(node->key);

  }

  else{

  node = cached_entries.back();

  cached_entries.pop_back();

  }

  node->key = key;

  node->data = data;

  cached_map[key] = node;

  attach(node);

  }

  cached_unlock();

  }

  template

  D LRUCache::Get(K key){

  cached_lock();

  Node *node = cached_map[key];

  if(node){

  detach(node);

  attach(node);

  cached_unlock();

  return node->data;

  }

  else{

  cached_unlock();

  return D();

  }

  }

  #endif

  测试用例:

  [cpp] view plaincopy

  /*

  Compile:

  g++ -o app app.cpp LRUCache.cpp -lpthread

  Run:

  ./app

  */

  #include

  #include

  #include "LRUCache.h"

  using namespace std;

  int

  main(void){

  //int k = 10 ,

  // max = 100;

  int k = 100000 ,

  max = 1000000;

  LRUCache * lru_cache = new LRUCache(k , true);

  int tmp = 0;

  for(int i = 0 ; i < 2*k ; ++i){

  tmp = rand() % max;

  lru_cache->Put(tmp, tmp + 1000000);

  cout<

  }

  for(int i = 0 ; i < k ; ++i){

  tmp = rand() % max;

  if(lru_cache->Get(tmp) == 0)

  cout《"miss : "<

  else

  cout《"hit : "< www.yzyedu.com

LRU缓存算法 - C++版的更多相关文章

  1. 面试挂在了 LRU 缓存算法设计上

    好吧,有人可能觉得我标题党了,但我想告诉你们的是,前阵子面试确实挂在了 RLU 缓存算法的设计上了.当时做题的时候,自己想的太多了,感觉设计一个 LRU(Least recently used) 缓存 ...

  2. 如何用LinkedHashMap实现LRU缓存算法

    阿里巴巴笔试考到了LRU,一激动忘了怎么回事了..准备不充分啊.. 缓存这个东西就是为了提高运行速度的,由于缓存是在寸土寸金的内存里面,不是在硬盘里面,所以容量是很有限的.LRU这个算法就是把最近一次 ...

  3. HashMap+双向链表手写LRU缓存算法/页面置换算法

    import java.util.Hashtable; class DLinkedList { String key; //键 int value; //值 DLinkedList pre; //双向 ...

  4. LRU缓存算法与pylru

    这篇写的略为纠结,算法原理.库都是现成的,我就调用了几个函数而已,这有啥好写的?不过想了想,还是可以介绍一下LRU算法的原理及简单的用法.   LRU(Least Recently Used,最近最少 ...

  5. Java 自定义实现 LRU 缓存算法

    背景 LinkedHashMap继承自HashMap,内部提供了一个removeEldestEntry方法,该方法正是实现LRU策略的关键所在,且HashMap内部专门为LinkedHashMap提供 ...

  6. LinkedHashMap实现LRU缓存算法

    LinkedHashMap的get()方法除了返回元素之外还可以把被访问的元素放到链表的底端,这样一来每次顶端的元素就是remove的元素. 构造函数如下: public LinkedHashMap  ...

  7. LRU缓存算法

    http://blog.csdn.net/beiyeqingteng/article/details/7010411 http://blog.csdn.net/wzy_1988/article/det ...

  8. 算法进阶面试题06——实现LFU缓存算法、计算带括号的公式、介绍和实现跳表结构

    接着第四课的内容,主要讲LFU.表达式计算和跳表 第一题 上一题实现了LRU缓存算法,LFU也是一个著名的缓存算法 自行了解之后实现LFU中的set 和 get 要求:两个方法的时间复杂度都为O(1) ...

  9. LRU缓存原理

    LRU(Least Recently Used)  LRU是近期最少使用的算法,它的核心思想是当缓存满时,会优先淘汰那些近期最少使用的缓存对象. 采用LRU算法的缓存有两种:LrhCache和DisL ...

随机推荐

  1. java实现DES加密与解密,md5加密

    很多时候要对秘要进行持久化加密,此时的加密采用md5.采用对称加密的时候就采用DES方法了 import java.io.IOException; import java.security.Messa ...

  2. linux浏览器,邮件客户端,输入法,双屏设置,应用软件,scrot -s截图,office

    搜狗输入法linux版:http://pinyin.sogou.com/linux/help.php win/linux同时支持比较好用的浏览器:maxthon,firefox,maxthon,ope ...

  3. thickbox 关于动态生成 无法跳出弹出框的问题

    问题描述: 用jQuery动态生成thickbox的连接代码,发现没有效果. 原因: thickbox在页面加载后,会给a,input,area等绑定弹出事件. 通过tb_init(’a.thickb ...

  4. 【归并排序】【逆序数】HDU 5775 Bubble Sort

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=5775 题目大意: 冒泡排序的规则如下,一开始给定1~n的一个排列,求每个数字在排序过程中出现的最远端 ...

  5. C++ 通过Thunk在WNDPROC中访问this指针实现细节

    本文代码使用了一些C++11特性,需要编译器支持.本文仅讨论x86_64平台的相关实现,x86平台理论上只需修改 thunk 相关机器码即可. THUNK的原理参见之前的一篇博文<C++ 通过T ...

  6. MVC控制器方法返回类型

    控制器公开控制器操作.操作是控制器上的方法,在浏览器的地址栏中输入特定 URL 时被调用.例如,假设要请求下面的 URL: http://localhost/Product/Index/3 在这种情况 ...

  7. Django学习笔记(五)—— 表单

    疯狂的暑假学习之  Django学习笔记(五)-- 表单 參考:<The Django Book> 第7章 1. HttpRequest对象的信息 request.path         ...

  8. linux crontab 定时命令

    一直认为Timer是比较好的实现定时器的方法,后来遇到在linux下的命令制定定时任务才发现,Timer的劣势所在,在Timer的时候很可能你的任务会被当做一个死程序被杀掉等等......上次一个同事 ...

  9. 数据库日期类型转换–HSQL

    最近遇到要用HSQL查询离某个时间的后十分钟的记录,不像Oracle和SqlServer中可以直接有函数转换,而是直接通过'+'来得到 Hsql Document -- standard forms ...

  10. linux 启动network后报错:device eth0 does not seem to be present, delaying initialization

    问题背景: 在vsphere client中部署ovf模板后启动linux 的network后提示:device eth0 does not seem to be present, delaying ...