我正在尝试制作一个基本的 HashMap。我正在检查一个元素是否存在于索引中,然后再将其插入到索引中。当我插入第一个元素时,它表示该位置已经存在一个元素。我已经通过调试器,我的所有值都符合预期,除了map[hash]
. 我期待一个nullptr,但它不会到来。 map[hash]
具有以下值:
- map[hash] 0xcdcdcdcd {key=??? value={...} next_element=??? } HashElement *
有人可以向我解释我在这里的误解吗?出乎意料的结果是 on line 21
。HashMap.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;
}