0

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!

2 Answers2

1

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.

nikolas
  • 8,707
  • 9
  • 50
  • 70
1

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.

Ivan Gritsenko
  • 4,166
  • 2
  • 20
  • 34
  • Can you explain me that for please? I really dont understand it. – Jean Alexander Mar 19 '16 at 22:56
  • @Jean Alexander, are you talking about finding the max value? – Ivan Gritsenko Mar 19 '16 at 22:57
  • Yes I am xD I dont understand that map.get or map.end what's that? – Jean Alexander Mar 19 '16 at 23:16
  • @Jean Alexander, there are iterators which allow you to iterate over items in data structure. It looks very similar to regular for loop iterating with variable `i`. However to access the value iterator is pointing to we should dereference it using either `->` or `*` operators. In this case iterator points to a `pair`, we are interested in the second part. Hence `it->second` which is current word counter. – Ivan Gritsenko Mar 19 '16 at 23:37