The code below reads in a list of 10 words and adds them to a map of string->int
ID: 3902205 • Letter: T
Question
The code below reads in a list of 10 words and adds them to a map of string->int. Add code to print out each word you were given with the number of times it was present in the list.
Hint: You just have to iterate through the map and print out each key/value pair with a space between them and a line break after.
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string, int> wordCounts;
for(int i = 0; i < 10; i++) {
string word;
cin >> word;
//add 1 to the count for that word
// anything that doesn't exist already
// becomes 0 when we try to read it!
wordCounts[word] = wordCounts[word] + 1;
}
//Do not modify anything on or above the line below this
//YOUR_CODE_BELOW
//YOUR_CODE
//YOUR_CODE_ABOVE
//Do not modify anything on or below the line above this
return 0;
}
Explanation / Answer
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string, int> wordCounts;
for (int i = 0; i < 10; i++) {
string word;
cin >> word;
//add 1 to the count for that word
// anything that doesn't exist already
// becomes 0 when we try to read it!
wordCounts[word] = wordCounts[word] + 1;
}
//Do not modify anything on or above the line below this
//YOUR_CODE_BELOW
//YOUR_CODE
map <string, int>::iterator it;
for(it = wordCounts.begin(); it != wordCounts.end(); it++) {
cout << it->first << " " << it->second << endl;
}
//YOUR_CODE_ABOVE
//Do not modify anything on or below the line above this
return 0;
}