美文网首页
LRU C++ map+list 实现

LRU C++ map+list 实现

作者: 咸鱼有只喵 | 来源:发表于2018-04-12 12: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();
            
            }
        }
    
    };
    
    

    相关文章

      网友评论

          本文标题:LRU C++ map+list 实现

          本文链接:https://www.haomeiwen.com/subject/daexkftx.html