LRU算法 C++

源码

#pragma once

#include <list>
#include <unordered_map>
using namespace std;
class LRUCache
{
public:
    LRUCache(int capacity) : cap(capacity)
    {
        m.reserve(capacity);
        m.max_load_factor(0.75);
    }

    int get(int key)
    {
        auto it = m.find(key);
        if (it == m.cend())
            return -1;
        l.splice(l.begin(), l, it->second);
        return it->second->second;
    }

    void put(int key, int value)
    {
        auto it = m.find(key);
        if (it != m.cend())
        {
            l.erase(it->second);
        }
        else if (m.size() >= cap)
        {
            int k = l.rbegin()->first;
            l.pop_back();
            m.erase(k);
        }
        l.emplace_front(make_pair(key, value));
        m[key] = l.begin();
    }

private:
    int cap;
    list<pair<int, int>> l;
    unordered_map<int, list<pair<int, int>>::iterator> m;
};

测试代码


#include "lru.hpp"
#include <iostream>
using namespace std;


int main() {
    LRUCache cache(2);
    cache.put(1, 1);
    cache.put(2, 2);
    cout << cache.get(1);       // 返回1

    cache.put(3, 3);            
    cout << cache.get(2);       // 返回-1

    cache.put(4, 4);             
    cout << cache.get(1);       // 返回-1
    cout << cache.get(3);       // 返回3
    cout << cache.get(4);       // 返回4
    
    cache.put(4,5);
    cout << cache.get(4);       // 返回5

    
    return 0;
}

posted @ 2023-11-10 18:30  天下太平  阅读(78)  评论(0)    收藏  举报