基本的な HashMap を作成しようとしています。要素を挿入する前に、要素がインデックスに存在するかどうかを確認しています。最初の要素を挿入すると、その位置に要素が既に存在すると表示されます。デバッガーを使用しましたが、. を除いてすべての値が期待どおりですmap[hash]。nullptr を期待していますが、まだ来ていません。 map[hash]次の値があります。
- map[hash] 0xcdcdcdcd {key=??? value={...} next_element=??? } HashElement *
誰かが私がここで誤解していることを説明してもらえますか? 予期しない結果が に発生しましline 21たHashMap.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;
}