LRU C++ map+list 实现

#include 
#include 
#include 
#include 
#include 
using namespace std;
class LRUChache{
private:
    struct elem{
        int value;
    };
    int size;

    typedef list mylist;
    typedef map 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();
        
        }
    }

};

你可能感兴趣的:(LRU C++ map+list 实现)