LRU缓存算法 - C++版

本文介绍了LRU(最近最少使用)缓存替换算法,并提供了C++实现。通过hashtable结合双向链表,实现了O(1)的时间复杂度的插入、查找和删除操作。代码中存在一些优化空间,如减少冗余操作和改进接口设计,但对理解LRU算法有一定帮助,适用于不同Linux环境。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


实现思路:   hashtable + 双向链表
时间复杂度:    插入,查找,删除:O(1)
空间使用情况:  O(N) :一个链表存储K个数据(stl的hash_map实际占的空间比较大).


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


代码:

#ifndef __LRUCACHE_H__
#define __LRUCACHE_H__

#include <vector>
#include <ext/hash_map>
#include <pthread.h>
#include <assert.h>

using namespace __gnu_cxx;

template <class K, class D>
struct Node{
    K key;
    D data;
    Node *prev, *next;
};

template <class K, class D>
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<K,D&g
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值