Jean Alexander
Jean Alexander

Reputation: 13

Find the most frequently word using hashmaps c++

I need to find the most frequently occurring word and return that value. I must use hash maps and the fuction would take a file name. This is what I've done so far but im very confused.

  int most_frequent_word(string filename)
  {
  string words;
  ifstream in(filename.c_str());
  unordered_map<string, int> word_map;
  while(in >> words)
  {

    for(int i = 0; i < 100; i++)
    {
        word_map[words[i]]++;
    }
   }
  return words;
  }

any help would be appreciated it. Thanks!

Upvotes: 0

Views: 1739

Answers (2)

Ivan Gritsenko
Ivan Gritsenko

Reputation: 4236

There are several issues in your code that might cause it to work not as expected.

First is for i loop. Why would you need taht loop at all? Leave it like this, you need to count words.

while(in >> words)
{
    word_map[words]++;
}

Rename words to word, actually you are reading one word here in >> words.

The third is return statement. You cannot return string when it is declared that function returns int.

However there is nothing to return yet, because so far we only know the number each word occurred. Run a loop to find max value.

int result = 0;
for(unordered_map<string, int>::iterator it = word_map.begin(); it != word_map.end(); it++)
    result = max(result, it->second);
return result;

Here word_map consists of pairs of a word and its number of occurrences. We need to iterate over all of these pairs looking for max occurrences. To do this we use iterator it.

Upvotes: 1

nikolas
nikolas

Reputation: 8975

I'm also confused!

for(int i = 0; i < 100; i++)
{
    word_map[words[i]]++;
}

What are you doing here? Where does the 100 come from? Why do you care for single letters of your words (which is what words[i] gets you)?

If I understand your task correctly, wouldn't it suffice to

++word_map[words];

instead?

Also why do you return words? It's a string, and your function should return and int. Instead find the largest value in your map and you're done.

Upvotes: 1

Related Questions