使用链接的哈希表的析构函数

时间:2013-11-19 06:47:35

标签: c++ hash hashtable

我有一个节点哈希表。在我的构造函数中,我将哈希表的每个元素初始化为NULL。我的代码编译,但在可执行文件结束后,它有以下错误: “调试断言失败!” 程序:/ pathname / 文件:F:\ DD \ vctools \ crt_bld \ self_x86 \ CRT \ SRC \ dbgdel.cpp 行:52

表达式:_BLOCK_TYPE_IS_VALID(pHead-> nBlockUse)

我对构造函数和析构函数的实现:

// Constructor
Hash::Hash() {
    for(int i = 0; i < tableSize; i++) {
        Hash_Table[i] = NULL; // Will be used to indicate an empty bucket
     } 
}
//
//
// Destructor
Hash::~Hash() {
    song* temp;
    song* temp_next;
    for(int i = 0; i < tableSize; i++) { // For every bucket
        if(NULL != Hash_Table[i]) { // If the bucket is not already empty
            temp = Hash_Table[i];
            while(NULL != temp) {
                delete[] temp->artist;
                delete[] temp->title;
                delete[] temp->playlists;
                delete[] temp->album;
                temp_next = temp->next;
                delete temp;
                temp = temp_next;
            } // end while loop
            Hash_Table[i] = NULL;
        } // end if
    } // end for loop
    delete[] Hash_Table;
} // end destructor

1 个答案:

答案 0 :(得分:0)

如果你还没有为song创建一个合适的析构函数。 delete temp应该调用song::~song,删除song以外song->next的所有成员。

Hash的析构函数变为:

Hash::~Hash() {
    song* temp;
    song* temp_next;
    for(int i = 0; i < tableSize; i++) { // For every bucket
        temp = Hash_Table[i];
        while(NULL != temp) {
            temp_next = temp->next;
            delete temp;
            temp = temp_next;
        } // end while loop
        Hash_Table[i] = NULL;
    } // end for loop
} // end destructor

我还删除了delete[] Hash_Table,因为您的构造函数不是new Hash_Table[]。您只需要delete[]表示您调用new[]的对象数组。

虽然没有看到完整的课程定义,但很难确定我的建议是否完全正确。正如其他人所建议的那样,您应该考虑使用map<>unordered_map<>而不是尝试滚动自己的哈希。当然,除非这是一项需要你的家庭作业。