【问题标题】:How to return number of occurrences in hash table c++?如何返回哈希表c ++中的出现次数?
【发布时间】:2021-03-17 03:55:42
【问题描述】:

我有一个文本文件,我使用 insert 方法将所有单词插入到哈希表中,然后我确实找到了假设返回写入单词的出现次数但它不返回任何内容的方法,这可能是错误的。因此,如果 if 条件中的单词进入它,但我不确定如何正确返回值变量

【问题讨论】:

  • 您可以随时使用std::unordered_multiset<std::string>::count

标签: c++ hashmap hashtable


【解决方案1】:

您已经完成了大部分工作,只需要一个小修复和一个小改动。

首先是修复。在HashNode

class HashNode
{
public:
    string key;
    int value;// constuctor accepts and assigns an int, not a string

public:
    HashNode(string key, int value)
    {
        this->key = key;
        this->value = value;
    }
    friend class HashTable; // not much point to friendship when the class 
                            // is entirely public
};

此更改在以后变得非常重要,因为现在在 insert 我们可以

void insert(string key)
{
    int value=1; //start with a count of 1.
    int index = hashCode(key) % this->capacity; 

    for (list<HashNode>::iterator it = buckets[index].begin();
         it != buckets[index].end(); 
         ++it)
        if (it->key == key)
        {
            it->value++; // count another instance 
            return;
        }
// rest unchanged

现在我们可以为哈希表中的每个单词显示一个计数。我们所要做的就是添加一个或两个函数以便我们可以显示它。

【讨论】:

    猜你喜欢
    • 2013-11-27
    • 2019-04-23
    • 2017-04-04
    • 2023-03-08
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    相关资源
    最近更新 更多