我的hashmap打印功能似乎有问题。它正在打印正确的值,但键不正确。在下面的代码中,我得到两个键/值对的用户输入,它只打印出第二个输入的键。
例如,对于第一对,我将输入12 /" e"和第二对,我将输入15 /" f"输出将是f | 12,f | 15.有人知道发生了什么吗?我认为它可能是char数组的东西,我会使用字符串,但我只能使用原语来完成这项任务。 100的char数组的大小只是一个任意大的数字,我认为用户密钥不会超过它。谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
typedef struct _node
{
char *key;
int value; /* For this, value will be of type int */
struct _node *next; /* pointer to the next node in the list */
} node;
/* HashMap class */
class HashMap
{
private:
node ** hashTable;
int numSlots;
public:
/* Initializes a hashmap given its set size */
HashMap(int size)
{
numSlots = size;
hashTable = new node*[size] ;
for (int i = 0; i < size; i++)
{
hashTable[i] = NULL;
}
}
/*** Hash function. ***/
int hash(char *s)
{
int i;
int sum = 0;
for (i = 0; * (s + i) != '\0'; i++)
{
sum += *(s + i);
}
return (sum % numSlots);
}
/* Create a single node. */
node *create_node(char *key, int value)
{
node *result = new node();
result->key = key;
result->value = value;
result->next = NULL;
return result;
}
/*
*Stores given key/value pair in hashmap
*returns boolean for success/failure
*/
void set (char* key, int value)
{
int keyValue = hash(key);
node *current = hashTable[keyValue];
node *original = current;
node *newNode;
if (current == NULL)
{
hashTable[keyValue] = create_node(key, value);
}
else
{
while (current != NULL)
{
current = current -> next;
}
if (current == NULL)
{
newNode = create_node(key, value);
newNode -> next = original;
hashTable[keyValue] = newNode;
}
}
}
/* Prints hash table */
void print_hash_table()
{
int i;
node *listIterator = NULL;
for (i = 0 ; i < numSlots ; i++)
{
listIterator = hashTable[i];
if (listIterator != NULL)
{
cout << listIterator->key << " | ";
while (listIterator != NULL)
{
cout << listIterator->value << " ";
listIterator = listIterator -> next;
}
cout << endl;
}
}
}
};
int main()
{
HashMap hash (128);
char key[100];
int value;
cout << "Enter element to be inserted: ";
cin >> value;
cout << "Enter key at which element to be inserted: ";
cin >> key;
hash.set(key, value);
cout << "Enter element to be inserted: ";
cin >> value;
cout << "Enter key at which element to be inserted: ";
cin >> key;
hash.set(key, value);
hash.print_hash_table();
return 0;
}
答案 0 :(得分:0)
您将字符指针传递给set
,并将该指针存储在地图中。然后,您更改key
中的内容,这将更改您已存储的第一个键的值,并在地图中再次存储相同的指针。所以两个键都具有相同的值。
这也会导致地图中的指针指向无效的内存区域(如果它们被删除或调用函数返回),将传入的数组放在范围之外。
当您将密钥存储在哈希映射中时,您需要复制密钥。