Menu
Coddy logo textTech

Recap - Word Frequency

Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 75 of 104.

challenge icon

Challenge

Easy

Let's build a Word Frequency Analyzer that processes text and displays word counts sorted by frequency. This is a classic text processing task that brings together all the STL components you've learned: map for counting, vector for sorting, iterators for traversal, and lambdas for custom sorting logic.

You'll organize your code across two files:

  • WordAnalyzer.h: Define a WordAnalyzer class that manages word counting and analysis.

    Your class should use a std::map<std::string, int> internally to store word counts. Implement these methods:

    • addWord(const std::string& word) — increments the count for the given word
    • getCount(const std::string& word) — returns the count for a specific word (0 if not found)
    • getTotalWords() — returns the total number of words added (sum of all counts)
    • getUniqueWords() — returns the number of unique words (size of the map)
    • printByFrequency() — prints all words sorted by frequency in descending order. For words with the same frequency, sort them alphabetically. Each line should display: word: count

    For printByFrequency(), you'll need to transfer the map contents to a vector of pairs, then use std::sort with a lambda that compares by count first (descending), then by word (ascending) for ties.

  • main.cpp: Read an integer n on the first line indicating how many words will follow. Then read n words, one per line.

    Create a WordAnalyzer, add all the words, then display:

    1. Print Total words: <count>
    2. Print Unique words: <count>
    3. Print Word frequencies: followed by calling printByFrequency()

For example, with input:

7
apple
banana
apple
cherry
banana
apple
date

The output should be:

Total words: 7
Unique words: 4
Word frequencies:
apple: 3
banana: 2
cherry: 1
date: 1

Notice how apple appears first (highest frequency), followed by banana, then cherry and date are sorted alphabetically since they have the same count.

Another example with input:

5
the
cat
the
sat
the

Output:

Total words: 5
Unique words: 3
Word frequencies:
the: 3
cat: 1
sat: 1

Try it yourself

#include <iostream>
#include <string>
#include "WordAnalyzer.h"

using namespace std;

int main() {
    int n;
    cin >> n;
    
    WordAnalyzer analyzer;
    
    // TODO: Read n words and add them to the analyzer
    
    // TODO: Print "Total words: <count>"
    
    // TODO: Print "Unique words: <count>"
    
    // TODO: Print "Word frequencies:" and call printByFrequency()
    
    return 0;
}

All lessons in Object Oriented Programming