C++ bootcamp · Lab 20

Word frequency

mediumMaps15 minLesson: Maps

Read the question, write C++ on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read words and print each distinct word with how many times it appears, one per line, sorted alphabetically.

Each line is the word, a space, then the count. std::map keeps its keys sorted for you.

Input. Words separated by whitespace.

Output. Lines of "word count", sorted alphabetically by word.

Examples

Example 1 — Alphabetical order: cat, dog, the.
Input
the cat the dog the
Output
cat 1
dog 1
the 3
Hint
  1. std::map<std::string, int> m; then m[word]++ tallies (a missing key starts at 0).
  2. Iterating a std::map visits keys in sorted order — print p.first and p.second.
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <iostream>
#include <map>
#include <string>

int main() {
  std::map<std::string, int> m;
  std::string w;
  while (std::cin >> w) m[w]++;
  for (auto& p : m) std::cout << p.first << " " << p.second << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.