Recap - Word Frequency
Part of the Object Oriented Programming section of Coddy's C++ journey. Lesson 75 of 104.
Challenge
EasyLet'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 aWordAnalyzerclass 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 wordgetCount(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 usestd::sortwith a lambda that compares by count first (descending), then by word (ascending) for ties.main.cpp: Read an integernon the first line indicating how many words will follow. Then readnwords, one per line.Create a
WordAnalyzer, add all the words, then display:- Print
Total words: <count> - Print
Unique words: <count> - Print
Word frequencies:followed by callingprintByFrequency()
- Print
For example, with input:
7
apple
banana
apple
cherry
banana
apple
dateThe output should be:
Total words: 7
Unique words: 4
Word frequencies:
apple: 3
banana: 2
cherry: 1
date: 1Notice 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
theOutput:
Total words: 5
Unique words: 3
Word frequencies:
the: 3
cat: 1
sat: 1Try 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
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy10STL Overview
STL Overview & PhilosophySTL ContainersIteratorsSTL AlgorithmsFunctors & Lambda ExpressionsRecap - Word Frequency2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic ContainerPractice on your own: Online C++ compiler