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
C++ Templates and Generic Programming
C++ STL Containers: map, set, unordered_map, queue and stack
C++ Algorithms and Iterators
Exercises & Assignments
Write a generic maximum template
Count the frequency of words with a map
Remove duplicates from a vector and keep the order
Interview Questions & Answers
What is the STL in C++?
What is the difference between std::map and std::unordered_map?
What is the difference between push_back and emplace_back in C++?
What is iterator invalidation in C++?
What is the difference between templates and macros in C++?