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::istringstreamreads word by word.std::mapkeeps 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 |