垃圾值被初始化为哈希表的值,尽管我专门将所有索引编码为-1



我不知道是否遗漏了一些非常简单的东西,但我在将空哈希表的所有值初始化为-1时遇到了问题。我有另一个带有ID号的数组(我将对其进行散列(。我将所有值初始化为-1,因为我可以稍后检查我的哈希数组的值是否为-1,然后我可以在不进行二次探测的情况下插入。

在我的构造函数中,我初始化表的大小。然后我创建一个具有该大小的数组。然后我把我的私有指针指向那个数组,这样我就可以一直访问它。从那里,我初始化我的表。。。我有一个关于构造函数中for循环的问题:

  • 我做arr[i]=-1还是table[i]=-1有关系吗?因为表指向所有的索引,对吗?而且arr[]显然可以访问它自己的索引。所以我不明白为什么这两种方式都很重要

如果有人能启发我,那就太好了。谢谢


HashTable::HashTable(int bsize)
{
this->tableSize= bsize; 
int arr[bsize]; //creating an array to hold hash values 
table = arr; //table pointer points to our new array
for(int i = 0; i < bsize; i++){ 
table[i] = -1; 
}
}
void  HashTable:: printTable(){
for(int i = 0; i < tableSize; i++){
cout << table[i] << endl;
}
}

这是我的班级

class HashTable
{
int tableSize = 40009;  // No. of buckets

// Pointer to an array containing buckets
int *table;
int numOfcolision =0;
public:
HashTable(int bsize);  // Constructor
// inserts a key into hash table
bool insert(int key);
// hash function to map values to key
unsigned int hashFunction(int key);
void printTable();
int getNumOfCollision();
int search(int key);
};

在构造函数中:

int arr[bsize]; //creating an array to hold hash values 

这是非标准C++。可变长度数组不是标准C++。在标准C++中,所有数组大小都是常量,这是在编译时而不是运行时确定的。但是,更重要的是,这是构造函数中的一个局部变量。

table = arr; //table pointer points to our new array

table大概是一个指针类成员。这将初始化类成员以指向构造函数中的本地数组。

但是一旦构造函数返回,数组就会被销毁,就像所有其他变量一样,这些变量是函数的本地变量。在类成员中使用指针会变成未定义的行为,对您来说,这表现为随机垃圾。

在C++中,数组不能这样工作。您需要将类中的指针/数组混合体替换为std::vector。您将在C++教材中找到更多关于如何使用std::vector的信息,以及许多使用它们的示例。

最新更新