简体   繁体   English

试图了解C ++中的哈希表代码

[英]Trying to understand hash table code in c++

I'm learning hash tables and found this code on another website, but am having trouble understanding the Insert(int key, int value) function. 我正在学习哈希表,并在另一个网站上找到了此代码,但是在理解Insert(int key,int value)函数时遇到了麻烦。 The function works well but I am wondering if there is extra code that is not needed or if I am not understanding it completely. 该功能运行良好,但是我想知道是否有不需要的额外代码,或者我是否完全不了解它。

Specifically, the else condition at the end of the function: 具体来说,函数结尾处的else条件:

else
{
     entry->value = value;
 }

It doesn't seem to ever reach that condition when I call that function using different parameters. 当我使用不同的参数调用该函数时,似乎从未达到那种条件。 Here is the rest of the code. 这是其余的代码。

#include<iostream>
#include<cstdlib>
#include<string>
#include<cstdio>
using namespace std;
const int TABLE_SIZE = 128;

class HashNode
{
public:
    int key;
    int value;
    HashNode* next;
    HashNode(int key, int value)
    {
        this->key = key;
        this->value = value;
        this->next = NULL;
    }
};

class HashMap
{
private:
    HashNode** htable;
    public:
    HashMap()
    {
        htable = new HashNode*[TABLE_SIZE];
        for (int i = 0; i < TABLE_SIZE; i++)
            htable[i] = NULL;
    }
    ~HashMap()
    {
        for (int i = 0; i < TABLE_SIZE; ++i)
        {
            HashNode* entry = htable[i];
            while (entry != NULL)
            {
                HashNode* prev = entry;
                entry = entry->next;
                delete prev;
            }
        }
        delete[] htable;
    }
    /*
     * Hash Function
     */
    int HashFunc(int key)
    {
        return key % TABLE_SIZE;
    }

    /*
     * Insert Element at a key
     */
    void Insert(int key, int value)
    {
        int hash_val = HashFunc(key);
        HashNode* prev = NULL;
        HashNode* entry = htable[hash_val];
        while (entry != NULL)
        {
            prev = entry;
            entry = entry->next;
        }
        if (entry == NULL)
        {
            entry = new HashNode(key, value);
            if (prev == NULL)
            {
                htable[hash_val] = entry;
            }
            else
            {
                prev->next = entry;
            }
        }
        else
        {
            entry->value = value;
        }
    }

    /* Search Element at a key
     */
    int Search(int key)
    {
        bool flag = false;
        int hash_val = HashFunc(key);
        HashNode* entry = htable[hash_val];
        while (entry != NULL)
        {
            if (entry->key == key)
            {
                cout << entry->value << " ";
                flag = true;
            }
            entry = entry->next;
        }
        if (!flag)
            return -1;
    }
};

int main()
{
    HashMap hash;
    hash.Insert(3, 7);
    hash.Search(3);
}

Any clarification is highly appreciated. 任何澄清都受到高度赞赏。

Thank you 谢谢

while (entry != NULL)

precedes 先于

if (entry == NULL) 

There is no way out of the while (entry != NULL) loop unless entry is NULL , guaranteeing that the else case is impossible. 除非entryNULL ,否则没有办法退出while (entry != NULL)循环,从而确保else情况是不可能的。

I believe that inside the while loop a test to see if the key is already present is required. 我相信,在while循环内需要进行测试以查看密钥是否已经存在。

while (entry != NULL)
{
    if (entry->key == key)
    {
        break;
    }
    prev = entry;
    entry = entry->next;
}

Off topic: Take a look at this question and answer for a suggestion on how to simplify your code: Using pointers to remove item from singly-linked list 主题外:查看此问题和答案,以获取有关如何简化代码的建议: 使用指针从单链接列表中删除项目

Example: 例:

/*
 * Insert Element at a key
 */
void Insert(int key, int value)
{
    int hash_val = HashFunc(key);
    HashNode** nextPtr = &htable[hash_val]; // Get a pointer to next, not to the entry
    // with a pointer to next we can keep going from next to next without 
    // ever needing a previous.
    // pick up a whole bunch of extra dereferencing *nextPtr, but an 
    // optimizing compiler is great at dealing with that extra overhead.
    while ((*nextPtr) != NULL) // loop until found or end
    {
        if ((*nextPtr)->key == key) // found key already in list
        {
            (*nextPtr)->value = value; // set value for key
            return; // all done.
        }
        nextPtr = &(*nextPtr)->next; // keep looking
    }
    *nextPtr = new HashNode(key, value); // didn't find. Add new node to end.
}

Addendum: Search only returns in the failure case. 附录: Search仅在失败的情况下返回。 A function that is declared as returning a value must always return a value. 声明为返回值的函数必须始终返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM