具有 class 值分段错误的地图

map with class value segmentation fault

设计并实现最近最少使用 (LRU) 缓存的数据结构。它应该支持以下操作:获取和设置。

get(key) - 如果缓存中存在键,则获取键的值(始终为正),否则 return -1。 set(key, value) - 如果键不存在则设置或插入值。当缓存达到其容量时,它应该在插入新项目之前使最近最少使用的项目无效。

#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;
}

所以我使用了一个映射和一个自定义双链表,如果我在初始化 LRU 后立即添加 cout 行,它似乎工作正常,但如果我不这样做,它会出现段错误,我不是很确定我应该如何管理 LRU 的内存使用(如果这是问题所在)

此外,如果有任何行可以写得更好(除了 std 命名空间)请告诉我,我将不胜感激。

您的程序表现出未定义的行为,因为 dlist 的成员变量 sizetailhead 在使用前未初始化。

使用

dlist() : dlist(0) {}
dlist(int capacity) : cap(capacity), size(0), tail(nullptr), head(nullptr) {}

这解决了我测试中的分段冲突问题。

我还建议向 node 添加一个构造函数:

struct node{

    node(int v) : val(v), next(nullptr), prev(nullptr) {}

    int val;
    struct node* next;
    struct node* prev; 
};

并使用

node* n=new node(value);

而不是

node* n=new node;
n->val=value;