I need to write a piece of code counts the string inputted and shows how many times each string occurred, essentially a frequency table of strings. So, user enters multiple strings (i.e. aaa, bbb, ccc, aaa) and the code is supposed to print out how many times each string occurs.
I know that I am supposed to use maps, but I have no clue how to proceed. I've looked at examples of frequency tables using maps, but I am lost. Any help would be greatly appreciated. Thank you!
I understand that keys are unique. But, am I able to generate keys automatically for each new entry that the user enters? I still don't know how I am supposed to use map to make a frequency table..
The while loop puts strings s into the map. If s isn't yet in the map it creates F[s] and sets its value to 1; if it is already there then it increases the value by 1. So it creates a frequency table. The while loop will run until cin can supply no more strings; then the condition of the stream will become 'false'.
The for loop outputs the frequency table by listing the pairs in the map. An iterator allows you to go through a container one by one when you don't have a natural array index. An iterator is a bit like a pointer, so you would get the element it points to by dereferencing as *i. Each element is a pair, with the first part accessed with '.first' and the second with '.second'. The iterator notation is incredibly verbose. You would get the same from for ( auto e : F ) cout << e.first << ":\t" << e.second << '\n'
which says: for each element in F print out the key (here, a string), then a colon and tab, then the value (here, the count).
Different case - upper or lower - will give different strings, so depending on what you want to do you may want to filter the strings before putting them in the map.