C++实现一个LRU缓存

cpp 复制代码
#include <iostream>
#include <unordered_map>
#include <list>

using namespace std;

class LRUCache {
private:
    int capacity;
    unordered_map<int, pair<int, list<int>::iterator>> cache;
    list<int> lru;

public:
    LRUCache(int capacity) {
        this->capacity = capacity;
    }

    int get(int key) {
        if (cache.find(key) == cache.end()) {
            return -1;
        }
        
        // 将访问的元素移动到最前面
        lru.splice(lru.begin(), lru, cache[key].second);
        
        return cache[key].first;
    }

    void put(int key, int value) {
        if (cache.find(key) == cache.end()) {
            if (cache.size() == capacity) {
                // 移除最久未使用的元素
                cache.erase(lru.back());
                lru.pop_back();
            }
            lru.push_front(key);
        }
        else {
            lru.splice(lru.begin(), lru, cache[key].second);
        }

        cache[key] = make_pair(value, lru.begin());
    }
};

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

    cache.put(4, 4);
    cout << cache.get(1) << endl;  // 输出 -1
    cout << cache.get(3) << endl;  // 输出 3
    cout << cache.get(4) << endl;  // 输出 4
    
    return 0;
}

这里使用了unordered_map来存储key和value的映射关系,以及每个key对应的list中的迭代器。list则存储了访问的顺序,最前面的元素是最近访问的,最后面的元素是最久未使用的。当插入新元素时,如果容量已满,则移除最久未使用的元素;当访问某个元素时,将其移动到最前面。这样就能保证LRU缓存的特性。

相关推荐
yqcoder12 分钟前
httpOnly 是什么,又有什么用?
开发语言·前端·javascript
山登绝顶我为峰 3(^v^)327 分钟前
C/C++ 交叉编译方法
java·c语言·c++
wuqingshun3141591 小时前
重写equals而不重写hashCode,会出什么问题?
java·开发语言
飞猪~1 小时前
LangChain python 版本 第一集
开发语言·python·langchain
李燚3 小时前
Go 项目怎么组织:DDD 4 层 vs MVC vs 脚本式
开发语言·golang·mvc·ddd·agent框架·eino
2zcode4 小时前
免费开源项目文档:基于MATLAB图像处理的啤酒瓶口缺陷检测系统设计与实现
开发语言·图像处理·matlab
人工智能时代 准备好了吗4 小时前
AI回答内容进入率监测:引用识别、文本匹配与语义判断
开发语言·人工智能·python
LONGZETECH4 小时前
新能源汽车动力电池检测仿真教学系统:C/S 分层架构与数字化实训落地全解析
大数据·c语言·开发语言·人工智能·架构·系统架构·汽车
郝学胜-神的一滴4 小时前
中级OpenGL教程 013:渲染器类架构设计与逐帧渲染流程详解
开发语言·c++·unity·游戏引擎·图形渲染·opengl·unreal
Metaphor6925 小时前
使用 Python 冻结 Excel 文件中的行、列和单元格
开发语言·python·excel