我尝试在C ++中实现自己的哈希图。
我的头是
class MyMap
{
public:
MyMap();
~MyMap();
int get(int key) const;
void put(int key, int value);
bool containsKey(int key);
Vector<int> keys() const;
int size();
void sanityCheck();
MyMap(const MyMap &myMap); // copy constructor
MyMap& operator= (const MyMap &myMap); // assignment overload
friend ostream &operator<<(ostream &out, MyMap &myMap);
friend istream &operator>>(istream &in, MyMap &myMap);
private:
struct key_val_pair {
int key;
int value;
key_val_pair* next;
};
typedef key_val_pair** bucketArray; // just renaming the pointer to pointer.
bucketArray createBucketArray(int nBuckets);
int hashFunction(int input) const;
bucketArray buckets;
int nBuckets;
int nElems;
int INIT_N_BUCKETS = 128;
};
我使用初始化地图
MyMap::MyMap() {
bucketArray buckets = createBucketArray(INIT_N_BUCKETS);
nBuckets = INIT_N_BUCKETS;
nElems = 0;
}
MyMap::bucketArray MyMap::createBucketArray(int nBuckets) {
bucketArray newBuckets = new key_val_pair*[nBuckets];
for (int i = 0; i < nBuckets; i++) {
newBuckets[i] = nullptr;
}
return newBuckets;
}
这是我的代码,将元素放入哈希图中
void MyMap::put(int key, int value) {
// compute hash;
int bucket = hashFunction(key) % nBuckets ;
key_val_pair *entry = buckets[bucket];
key_val_pair *prev = nullptr;
if(entry == nullptr) {
entry = new key_val_pair;
entry->key = key;
entry->value = value;
entry->next = nullptr;
buckets[bucket] = entry;
nElems++;
}
else{
while(entry && entry->key != key){
prev = entry;
entry = entry->next;
}
if(!entry){
entry = new key_val_pair;
entry->key = key;
entry->value = value;
entry->next = nullptr;
if(!prev) buckets[bucket] = entry;
else prev->next = entry;
nElems++;
}
else{
entry->value = value;
}
}
}
现在,这是很奇怪的部分,即使在初始化之后也是如此。例如,我让
MyMap m = MyMap();
。然后我输入了从0到100的(i,i)对。我发现并不是我所有的buckets [i]都是空指针(我在句子中添加了buckets[bucket] == null
这样的句子)!在我将对放入地图之前。有些是,有些不是!这件事怎么会发生?当我将它们全部初始化为
nullptr
时?仅供参考,在构造函数中,我检查了所有bucket [i]的确是
nullptr
。这个错误使我发疯....有人可以帮我吗?谢谢!
最佳答案
您在构造函数中声明了另一个bucketarray,但没有将其分配给类中的成员:bucketArray buckets = createBucketArray(INIT_N_BUCKETS);
应该:
buckets = createBucketArray(INIT_N_BUCKETS);
甚至更好,像这样初始化所有成员:
MyMap::MyMap()
:
INIT_N_BUCKETS(128),
buckets(createBucketArray(INIT_N_BUCKETS)),
nBuckets(INIT_N_BUCKETS),
nElems(0)
{ }
您还必须在类中将
INIT_N_BUCKETS
移到更高的位置,因为初始化时顺序很重要。示例代码:
https://ideone.com/b8RN1Q
关于c++ - 在C++中实现hashmap期间发生了奇怪的事情,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45957135/