LRU算法 c++手写 map

本文介绍了一种使用双向链表和哈希表实现的LRU(最近最少使用)缓存算法。通过C++代码详细展示了如何进行数据的插入、删除及查找操作,并保持缓存的最新使用状态。

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

#include<iostream>
using namespace std;
#include<queue>
#include<map>
#include<string.h>



struct cachenode
{
    int key;
    int value;
    cachenode *pre;
    cachenode *next;
    cachenode(int key_t,int value_t)
    {
        key=key_t;
        value=value_t;
        pre=NULL;
        next=NULL;
    }
};

class lrucache
{
private:
    int lrucache_size;
    cachenode *head;
    cachenode *tail;
    map<int,cachenode*>mp;
public:
    lrucache(int size_tt)
    {
        lrucache_size=size_tt;
        head=NULL;
        tail=NULL;
    }
    void set_data(int key,int value)
    {
        map<int,cachenode*>::iterator it=mp.find(key);
        if(it!=mp.end())
        {
            cachenode *temp=it->second;
            temp->value=value;
            remove_data(temp);
            set_head(temp);
        }
        else
        {
            cachenode *new_node=new cachenode(key,value);
            if(mp.size()>=lrucache_size)
            {
                map<int,cachenode*>::iterator it=mp.find(tail->key);
                remove_data(tail);
                mp.erase(it);

            }
            set_head(new_node);
            mp[key]=new_node;
        }
    }
    int get_data(int key)
    {
        map<int,cachenode*>::iterator it=mp.find(key);
        if(it!=mp.end())
        {
            cachenode *temp=it->second;
            remove_data(temp);
            set_head(temp);
            return temp->value;
        }
        else
            return -1;
    }
    void remove_data(cachenode *node)
    {
        if(node->pre!=NULL)
            node->pre->next=node->next;
        else
            head=node->next;

        if(node->next!=NULL)
        {
            node->next->pre=node->pre;
        }
        else
        {
            tail=node->pre;
        }
    }
    void set_head(cachenode *node)
    {
        node->next=head;
        node->pre=NULL;
        if(head!=NULL)
        {
            head->pre=node;
        }
        head=node;
        if(tail==NULL)
            tail=head;

        //head=node;

    }

};

int main()
{
    lrucache *t_lrucache;
    t_lrucache=new lrucache(2);
    t_lrucache->set_data(2,1);
    t_lrucache->set_data(3,4);
    cout<<t_lrucache->get_data(3)<<endl;
    //cout<<"first"<<endl;
    t_lrucache->set_data(5,7);

    //cout<<"end"<<endl;
    cout<<t_lrucache->get_data(2)<<endl;
    cout<<t_lrucache->get_data(5)<<endl;
}

### C++ 中虚拟内存管理的实现机制 #### 1. 虚拟内存的概念 虚拟内存是一种由操作系统提供的抽象层,它允许应用程序像使用连续地址空间一样访问物理内存。尽管实际可用的物理内存可能有限,但通过分页技术以及磁盘交换区的支持,虚拟内存使得程序能够运行在更大的逻辑地址空间上[^3]。 #### 2. C++ 的虚拟内存支持 C++ 并不直接提供对虚拟内存的操作接口,而是依赖底层操作系统的功能来完成这些任务。然而,在某些情况下,可以通过自定义的方式来模拟虚拟内存的行为。例如,利用 STL 容器或者手写的缓存策略(如 LRU 缓存)来间接实现类似的机制[^5]。 #### 3. 使用 `new` 和 `delete` 进行动态内存分配 虽然传统的 C 风格函数(如 `malloc()` 和 `free()`)也可以用于 C++ 程序中,但是推荐采用更为现代的方法——即通过 `new` 关键字请求新的对象实例并返回其指针,而当不再需要此对象时则调用相应的 `delete` 来销毁之。这种方式不仅简化了语法结构而且还提供了构造/析构过程中的初始化能力[^1]。 #### 4. 页面置换算法 - LRU (Least Recently Used) 为了更好地管理和优化大容量数据集上的频繁读取需求,可以引入类似于 LRUsuch algorithms within our custom implementations of virtual memory systems inside CPP applications.[^5] 下面给出一个简单的基于双向链表和哈希映射实现的LRU Cache例子: ```cpp #include <iostream> #include <unordered_map> #include <list> template<typename KeyType, typename ValueType> class LRUCache { private: std::list<std::pair<KeyType, ValueType>> cache; std::unordered_map<KeyType, typename std::list<std::pair<KeyType, ValueType>>::iterator> map_; size_t capacity_; public: explicit LRUCache(size_t cap):capacity_(cap){} void put(const KeyType& key,const ValueType &value){ auto it=map_.find(key); if(it != end(map_)){ cache.erase(it->second); map_.erase(it); } while(cache.size()>=capacity_) { const auto& lastKey =cache.back().first ; map_.erase(lastKey ); cache.pop_back(); } cache.emplace_front(std::make_pair(key,value)); map_[key]=begin(cache); } bool get(const KeyType& key ,ValueType &result)const{ auto it=map_.find(key); if(it==end(map_))return false; result=(it->second)->second; return true; } }; int main(){ LRUCache<int,std::string> lruCache(3); lruCache.put(1,"one"); lruCache.put(2,"two"); lruCache.put(3,"three"); std::string res; if(lruCache.get(1,res)) std::cout<<res<<"\n"; //prints one lruCache.put(4,"four"); if(!lruCache.get(2,res)) std::cerr<<"Not Found\n";//since two was evicted due to least usage. } ``` 上述代码片段展示了一个基本版本的 LRU 缓存类模板设计思路及其工作原理说明。 #### 5. 内存泄漏预防措施 由于 C/C++ 不具备垃圾收集器这样的自动化工具帮助清理废弃的对象占用的空间资源,所以开发者必须格外小心处理好每一个动态创建出来的实体生命周期结束后的释放事宜以免造成严重的后果比如堆溢出等问题发生[^4]。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值