c++实现LRU算法

c++实现LRU算法

#include <iostream>
#include <list>
#include <utility>
#include <vector>
#include <unordered_map>
#include <memory>

using namespace std;

class LRUCache {

public:
    unordered_map<int, list<pair<int, int>>::iterator> keyToVal{};
    list<pair<int, int>> Cache{};
    int cap;
public:
    explicit LRUCache(int _cap) : cap(_cap) {

    }

    int get(int key) {
        if (keyToVal.find(key) == keyToVal.end()) {
            return -1;
        }
        auto val = keyToVal.at(key)->second;
        makeRecently(key);
        return val;
    }


    void put(int key, int val) {
        if (keyToVal.find(key) != keyToVal.end()) {
            deleteKey(key);
            addRecently(key, val);
            return;
        }

        if (keyToVal.size() >= cap) {
            removeLeastUsage();
        }

        addRecently(key, val);
    }

private:

    void makeRecently(int key) {
        auto node = *keyToVal.at(key);
        Cache.erase(keyToVal.at(key));
        Cache.push_front(node);
        keyToVal[key] = Cache.begin();
    }

    void addRecently(int key, int val) {
        auto node = std::make_pair(key, val);
        Cache.push_front(node);
        keyToVal[key] = Cache.begin();
    }

    void removeLeastUsage() {
        auto key = Cache.back().first;
        keyToVal.erase(key);
        Cache.pop_back();
    }

    void deleteKey(int key) {
        auto node = keyToVal.at(key);
        Cache.erase(node);
        keyToVal.erase(key);
    }
};


int main() {
    std::cout << "Hello, World!" << std::endl;
    LRUCache lRUCache(2);
    lRUCache.put(1, 1); // 缓存是 {1=1}
    lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
    auto res = lRUCache.get(1);    // 返回 1
    lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
    res = lRUCache.get(2);    // 返回 -1 (未找到)
    lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
    res = lRUCache.get(1);    // 返回 -1 (未找到)
    res = lRUCache.get(3);    // 返回 3
    res = lRUCache.get(4);    // 返回 4
    return 0;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值