映射与类值分割故障

map with class value segmentation fault

本文关键字:分割 故障 映射      更新时间:2023-10-16

为LRU (Least Recently Used)缓存设计并实现一个数据结构。它应该支持以下操作:get和set。

get(key) -如果键存在于缓存中,则获取键的值(将始终为正),否则返回-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后添加计数行,它似乎可以正常工作,但如果我不这样做,它会有seg故障,我和不太确定我应该做些什么来管理LRU的内存使用(如果这是问题)

如果有任何行可以写得更好(除了std命名空间),请告诉我,我真的很感激。

您的程序显示未定义的行为,因为dlist的成员变量size, tailhead在使用之前没有初始化。

使用

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;