垃圾值被初始化为我的散列 table 的值,即使我专门将所有索引编码为 -1

Garbage values are being initialized as the values of my hash table even though I specifically code all indices to -1

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

在我的构造函数中,我初始化了 table 大小。然后我创建一个具有该大小的数组。然后我将我的私有指针指向那个数组,这样我就可以随时访问它。从那里开始,我初始化 table... 我对构造函数中的 for 循环有疑问:

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


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

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 大概是一个指针 class 成员。这会将 class 成员初始化为指向构造函数中的本地数组。

但是一旦构造函数returns,数组就被销毁了,就像所有其他局部变量一样,在它们被声明的地方发挥作用。在 class 成员中使用指针成为未定义的行为,对您来说,它表现为随机垃圾。

数组在 C++ 中不是这样工作的。您需要将 class 中的 pointer/array 混合替换为 std::vector。您将在您的 C++ 教科书中找到有关如何使用 std::vector 的更多信息,以及许多使用它们的示例。