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

相关推荐
沐怡旸11 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥11 小时前
C++ 内存管理
c++
博笙困了17 小时前
AcWing学习——双指针算法
c++·算法
感哥18 小时前
C++ 指针和引用
c++
感哥1 天前
C++ 多态
c++
沐怡旸1 天前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4162 天前
Javer 学 c++(十三):引用篇
c++·后端
感哥2 天前
C++ std::set
c++
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法
博笙困了2 天前
AcWing学习——差分
c++·算法