map with class value segmentation fault

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) – Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) – Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

#include <iostream>
#include <map>
using namespace std;
struct node{
    int val;
    struct node* next;
    struct node* prev; 
};
class dlist{
    public:
        dlist(){}
        dlist(int capacity){
            cap=capacity;
        }
        void add(int value){
            node* n=new node;
            n->val=value;
            if (size==0){
                size++;
                tail=n;
                head=tail;
            }
            else {
                if (size==cap){
                    node* buf=head;
                    head=head->next;
                    head->prev=NULL;
                    delete buf;
                    size--;
                }
                tail->next=n;
                n->prev=tail;
                tail=n;
                size++;
            }
        }
        int getVal(){
            if (tail==NULL)
                return -1;
            return tail->val;
        }
    private:
        int cap;
        int size;
        node* tail;
        node* head;
};

class LRUCache{
    public:
        LRUCache(int capacity) {
            cap=capacity;
        }
        int get(int key) {
            if(cap!=0&&cache.find(key)!=cache.end())
                return cache[key].getVal();
            return -1;
        }
        void set(int key, int value) {
            if (cap==0)
                return;
            if(cache.find(key)==cache.end()){
                dlist d=dlist(cap);
                cache.insert(make_pair(key,d));
            }
            cache[key].add(value);
        }
    private:
        int cap;
        map<int,dlist> cache;
};

int main()
{
   LRUCache lru(3);
                   cout<<"asd";
   lru.set(1,9);
   lru.set(1,8);
   lru.set(1,1);
   lru.set(1,7);
   lru.set(2,9);
    cout<<lru.get(1)<<endl;
    cout<<lru.get(2)<<endl;
    cout<<lru.get(3)<<endl;
   return 0;
}

so I used a map and a custom double linked list, it seems to working fine with if I add the cout line right after initializing LRU, but it will have seg fault if I don’t, I and not very sure what should I do to manage the memory use of LRU(if this is the problem)

Also if there’s any line that could be better written(aside from std namespace) please tell me, I would really appreciate that.


Source: syntax

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.