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缓存的特性。

相关推荐
小小龙学IT3 分钟前
Boost.Interprocess 开源 C++ 进程间通信库深度解析
c++·开源
倒头就睡的小比特5 天前
算法竞赛C++常用的STL
c++·算法
weilx12345 天前
C++笔记-文件IO-<fcntl.h>
c++
小羊没烦恼!5 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
伞伞悦读5 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
Smileyqp沛沛5 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
C语言小火车5 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光5 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
吞下星星的少年·-·5 天前
C++ 萌新语法入门篇
c++·算法比赛
霍霍的袁6 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio