0

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

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

有人可以向我解释我在这里的误解吗?出乎意料的结果是 on line 21HashMap.cpp以下是相关代码:

哈希映射.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);
};

哈希映射.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);
    }
}

哈希元素.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();
};

哈希元素.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;
}
4

2 回答 2

1

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

map = new HashElement*[size];

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

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

map = new HashElement*[size]();
                            ^^
于 2015-03-01T17:37:39.123 回答
1
map = new HashElement*[size];

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

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

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

...在构造函数中

于 2015-03-01T17:38:55.063 回答