Count the frequency of words with a map

Description: Count the words of "the cat and the dog and the bird", and print them in alphabetical order.

Hint:

  • std::istringstream reads word by word. std::map keeps sorted keys.

Solution

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

int main() {
    std::istringstream in("the cat and the dog and the bird");
    std::map<std::string, int> count;
    std::string word;
    while (in >> word) {
        count[word]++;
    }
    for (const auto& [w, n] : count) {
        std::cout << w << " = " << n << '\n';
    }
}
Output

and = 2
bird = 1
cat = 1
dog = 1
the = 3

How it works

  • count[word]++ creates the key with 0 when it is new, and then adds 1.

Read STL Containers.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.