我正在尝试写一个哈希映射,但是构造函数不会分配内存,有人可以帮助我,我是新手代码,对不起打扰你们,但我会非常感谢你的帮助。< / p>
class HashMap {
private:
HashEntry **table;
int count;
int TABLE_SIZE;
public:
HashMap()
{
TABLE_SIZE = 128;
table = new HashEntry*[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
table[i] = NULL;
count=0;
}
}
class HashEntry
{
private:
int key;
int value;
public:
HashEntry(){}
~HashEntry(){}
HashEntry(int key, int value) {
this->key = key;
this->value = value;
}
int getKey() {
return key;
}
int getValue() {
return value;
}
void setValue(int value) {
this->value = value;
}
};
运行时,
table = new HashEntry*[TABLE_SIZE];
表无法读取内存,我是编码的新手,请给我一些帮助,谢谢!
答案 0 :(得分:0)
您可以通过malloc()
创建对象数组,这样您就可以动态分配内存。我还无法测试这段代码,但它应该按原样运行:
HashEntry* table;
int TABLE_SIZE;
HashMap(){
TABLE_SIZE = 128;
table = (HashEntry*)malloc(sizeof(HashEntry) * TABLE_SIZE);
for(int i = 0; i < TABLE_SIZE; i++){
table[i] = NULL; //If you want to create your objects, you need to replace `NULL` with `new HashEntry()`
}
}