0

基本的な HashMap を作成しようとしています。要素を挿入する前に、要素がインデックスに存在するかどうかを確認しています。最初の要素を挿入すると、その位置に要素が既に存在すると表示されます。デバッガーを使用しましたが、. を除いてすべての値が期待どおりですmap[hash]。nullptr を期待していますが、まだ来ていません。 map[hash]次の値があります。

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

誰かが私がここで誤解していることを説明してもらえますか? 予期しない結果が に発生しましline 21HashMap.cpp。関連するコードは次のとおりです。

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

そうではありません。「単純な古いデータ」またはの場合POD、その内容はデフォルトでは初期化されません。それらを明示的に初期化する必要があります。

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

...コンストラクタで

于 2015-03-01T17:38:55.063 に答える