LRU C++ map+list 实现

2018-04-12  本文已影响18人  咸鱼有只喵
#include <iostream>
#include <list>
#include <map>
#include <stack>
#include <queue>
using namespace std;
class LRUChache{
private:
    struct elem{
        int value;
    };
    int size;

    typedef list<elem> mylist;
    typedef map<int, mylist::iterator> myMap;
    mylist list;
    myMap map;
public:
    LRUChache(int size){
        this->size = size;
    }
    
    int get(int key){
        auto it = map.find(key);
        if(it == map.end()){return  -1;}
        else{
            auto list_it = map[key];
            int value = list_it->value;
            elem elemm;
            elemm.value = value;
            list.erase(list_it);
            list.push_front(elemm);
            map[key] = list.begin();
            return list.begin()->value;
        }
        
    }
    
    void put(int key,int value){
        auto it = map.find(key);
        //找不到要分满和不满两种情况
        if(it == map.end()){
            if (list.size()==size){
                map.erase(list.back().value);
                list.pop_back();
            }
            list.push_front(elem{value});
            map[key] = list.begin();
        // 找到直接调整顺序就可以了
        }else{
            auto list_it = map[key];
            elem ee;
            ee.value = value;
            list.erase(list_it);
            list.push_front(ee);
            map[key] = list.begin();
        
        }
    }

};

上一篇下一篇

猜你喜欢

热点阅读