未声明的数组元素缺少 nullptr

Missing nullptr for undeclared array element

我正在尝试制作一个基本的 HashMap。在将元素插入索引之前,我正在检查它是否存在于索引中。当我插入第一个元素时,它说该位置已经存在一个元素。我已经通过调试器,我的所有值都符合预期,除了 map[hash]。我期待一个 nullptr,但它不会出现。 map[hash] 具有以下值:

-       map[hash]   0xcdcdcdcd {key=??? value={...} next_element=??? }  HashElement *

有人可以向我解释一下我在这里的误解吗?意外结果发生在 HashMap.cppline 21 上。这是相关代码:

HashMap.h

#pragma once
#include <string>

#include "HashElement.h"

class HashMap
{
private:
    HashElement **map;
    int size;
public:
    HashMap(int);
    ~HashMap();
    int GetHash(int);
    void Put(int, std::string);
};

HashMap.cpp

#include "HashMap.h"

#include <string>

HashMap::HashMap(int _size)
{
    size = _size;
    map = new HashElement*[size];
}

HashMap::~HashMap()
{
}

int HashMap::GetHash(int _key){
    return _key % size;
}

void HashMap::Put(int _key, std::string _value){
    int hash = GetHash(_key);
    if (!map[hash]){  //Anticipated to be nullptr on first Put, but it skips to else
        map[hash] = new HashElement(_key, _value);
    }
    else{
        HashElement *lastElement = map[hash];
        while (lastElement->next_element){
            lastElement = lastElement->next_element;
        }
        lastElement->next_element = new HashElement(_key, _value);
    }
}

HashElement.h

#pragma once

#include <string>

class HashElement
{
private:
    int key;
    std::string value;
public:
    HashElement(int, std::string);
    ~HashElement();
    HashElement *next_element;
    int get_key();
    std::string get_value();
};

HashElement.cpp

#include "HashElement.h"

HashElement::HashElement(int _key, std::string _value)
{
    key = _key;
    value = _value;
}

HashElement::~HashElement()
{
}

int HashElement::get_key(){
    return key;
}

std::string HashElement::get_value(){
    return value;
}

map[hash] 不是 nullptr 因为你还没有初始化它。

map = new HashElement*[size];

map 数组中的每个元素在该行后都有一个随机值。

要解决此问题并将所有元素初始化为 nullptr:

map = new HashElement*[size]();
                            ^^
map = new HashElement*[size];

在这里,您在堆上实例化了一个 size 指针数组。据我了解你的问题,你假设所有实例化的指针,在这个 new 数组中,将是 nullptr.

事实并非如此。对于 "plain old data" 或 POD,其内容默认不初始化。您必须显式初始化它们:

for (size_t i=0; i<size; ++i)
    map[i]=0;

...在构造函数中