mike jetski
mike jetski

Reputation: 23

How to return number of occurrences in hash table c++?

I have a text file and i inserted all words to the hash table with insert method, and then i did find method that suppose to return number of occurrence of word written but it does not return anything, what can be wrong. So if the word in the if condition it enteres it, but i am not sure how to correctly return value variable

Upvotes: 1

Views: 348

Answers (1)

user4581301
user4581301

Reputation: 33931

You're most of the way there and just need a small fix and a small change.

First a the fix. In 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
};

This change becomes really important later because now in insert we can

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

Now we have a count we can display for each word in the hash table. All we have to do is add a function or two so we can display it.

Upvotes: 1

Related Questions