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安全HTTPS工具类

    import java.io.FileInputStream; import java.security.KeyStore; import java.security.SecureRandom; im ...

  2. 14.4.4 Redo Log Buffer

    14.4.4 Redo Log Buffer redo log buffer 是内存区域持有数据被写入到redo log. Redo log buffer size 是通过 innodb_log_bu ...

  3. 自己的缺省(sheng)源

    write无力吐槽了 #include <cstdio> #include <iostream> #include <algorithm> #include < ...

  4. HDOJ 1014 Uniform Generator(公约数问题)

    Problem Description Computer simulations often require random numbers. One way to generate pseudo-ra ...

  5. Scala 编程(四)内建控制结构

    if 表达式 Scala 的 if 如同许多其它语言中的一样工作.它测试一个状态并据其是否为真,执行两个分支中的一个: var filename = "default.txt" i ...

  6. LeetCode题目答案索引

    LeetCode-Two Sum LeetCode-Median of Two Sorted Arrays LeetCode-Longest Substring Without Repeating C ...

  7. KMP学习

    刚才看了(连接)写的翻译,把kmp算法的工作过程讲的很不错,kmp算法的核心是next,next为什么要那么赋值?其实就是前缀和后缀的最大匹配值,用这个值在匹配失败的时候可以跳过一个不必要的匹配.   ...

  8. [置顶] 【Git入门之九】解决冲突

    原创作品,转载请标明:http://blog.csdn.net/jackystudio/article/details/12309531 1.多人协作冲突 如果多人同时修改了同一个文件,那会出现什么样 ...

  9. Purchase Document Open Interface(PDOI)

    PO模块也有自己的接口表,多用于把其他业务系统在Oracle EBS系统生成采购订单记录. Table Name Description Type PO_HEADERS_INTERFACE This ...

  10. 完整版的OpenLDAP搭建全过程

    总结:          先写总结,再写正文,嘿嘿嘿.这还是第一次认真的写个文档,写个总结,哈哈.大概在一个月前,第一次听说这个东西,完全没有概念,刚开始的时候看理论的知识,看了几次之后就没看了,看不 ...