LRU算法实现

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是LRU算法的C++实现: ```c++ #include <iostream> #include <list> #include <unordered_map> using namespace std; class LRUCache { public: LRUCache(int capacity) { cap = capacity; } int get(int key) { auto it = cache.find(key); if (it == cache.end()) { return -1; } // 将当前访问的节点移到链表头部,并更新哈希表中该节点的地址 cacheList.splice(cacheList.begin(), cacheList, it->second); it->second = cacheList.begin(); return it->second->second; } void put(int key, int value) { auto it = cache.find(key); if (it != cache.end()) { // 如果 key 已经存在,先删除旧的节点 cacheList.erase(it->second); } // 插入新节点到链表头部,并在哈希表中添加该节点 cacheList.push_front(make_pair(key, value)); cache[key] = cacheList.begin(); // 如果超出缓存容量,删除链表尾部节点,并在哈希表中删除对应的项 if (cache.size() > cap) { int k = cacheList.rbegin()->first; cacheList.pop_back(); cache.erase(k); } } private: int cap; list<pair<int, int>> cacheList; unordered_map<int, list<pair<int, int>>::iterator> cache; }; int main() { LRUCache cache(2); cache.put(1, 1); cache.put(2, 2); cout << cache.get(1) << endl; // 输出 1 cache.put(3, 3); cout << cache.get(2) << endl; // 输出 -1,因为缓存中已经删除了 key 为 2 的项 cache.put(4, 4); cout << cache.get(1) << endl; // 输出 -1,因为缓存中已经删除了 key 为 1 的项 cout << cache.get(3) << endl; // 输出 3 cout << cache.get(4) << endl; // 输出 4 return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值