C++实现一个LRU缓存

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>