C++: Word counts with map

Read n words and print how many times each different word appears, in dictionary order. Use a map<string, int>.

What to build

A word counter built on map<string, int>.

Requirements

  • Add 1 to count[w] for every word.
  • Loop over the map to print the results.
  • Print each word once, in dictionary order.

Input

The first line has n (1 ≤ n ≤ 1000). The next line has the n words (lowercase letters only).

Output

One line for each different word, in dictionary order: the word, a space, its count.

Constraints

1 ≤ n ≤ 1000, and the words are lowercase.

Example

Input:

7
the cat and the dog and the

Output:

and 2
cat 1
dog 1
the 3

Why it works

A map keeps its keys sorted, and count[w] starts a missing word at 0, so one loop to count and one to print give the answer.

Examples

Example 1 · Input
7
the cat and the dog and the
Expected output
and 2
cat 1
dog 1
the 3
Example 2 · Input
1
hello
Expected output
hello 1

Hints

Hint 1

map<string, int> count; then count[w]++ for every word.

Hint 2

A map keeps its keys sorted, so a range-for gives the words in dictionary order.

Hint 3

Each item is a pair: p.first is the word, p.second the count.

Solution

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

int main() {
    int n;
    cin >> n;
    map<string, int> count;
    for (int i = 0; i < n; i++) {
        string w;
        cin >> w;
        count[w]++;
    }
    for (auto& p : count) cout << p.first << " " << p.second << endl;
    return 0;
}

Lesson: The standard library: vector, string, map and sort →