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

相关推荐
云和数据.ChenGuang1 小时前
Ascend C 核心技术特性
c语言·开发语言
kyle~4 小时前
C++---value_type 解决泛型编程中的类型信息获取问题
java·开发语言·c++
NiNi_suanfa6 小时前
【Qt】Qt 批量修改同类对象
开发语言·c++·qt
小糖学代码7 小时前
LLM系列:1.python入门:3.布尔型对象
linux·开发语言·python
Data_agent7 小时前
1688获得1688店铺详情API,python请求示例
开发语言·爬虫·python
信奥胡老师7 小时前
苹果电脑(mac系统)安装vscode与配置c++环境,并可以使用万能头文件全流程
c++·ide·vscode·macos·编辑器
妖灵翎幺7 小时前
C++ 中的 :: 操作符详解(一切情况)
开发语言·c++·ide
Halo_tjn8 小时前
虚拟机相关实验概述
java·开发语言·windows·计算机
star _chen8 小时前
C++实现完美洗牌算法
开发语言·c++·算法
周杰伦fans8 小时前
pycharm之gitignore设置
开发语言·python·pycharm