C++: Count the words

Count how often each word appears.

What to build

A tally that comes out sorted automatically.

Requirements

  • Read words until the input ends.
  • Print each different word and its count, in alphabetical order.

Input

Words separated by spaces or new lines.

Output

One line per different word.

Constraints

There are from 1 to 10000 words.

Example

Input:

the cat the dog

Output:

cat 1
dog 1
the 2

Why it works

counts[word] creates the entry with a value of 0 the first time, so the same line both starts and updates a count. The map keeps its keys sorted.

Examples

Example 1 · Input
the cat the dog
Expected output
cat 1
dog 1
the 2
Example 2 · Input
one
Expected output
one 1

Hints

Hint 1

counts[word]++ works even the first time.

Hint 2

Looping over the map gives the words in order.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> counts;
    string word;
    while (cin >> word) {
        counts[word]++;
    }
    for (const auto& item : counts) {
        cout << item.first << " " << item.second << endl;
    }
    return 0;
}

Lesson: Maps and sets →