Recap - Word Frequency
Part of the Logic & Flow section of Coddy's C++ journey — lesson 29 of 56.
Challenge
EasyCreate a program that counts word frequencies in a text passage using a std::map. Your program will track how many times each unique word appears and then report the frequency of a specific word.
The following inputs will be provided:
- An integer
nrepresenting the number of words in the text - Then
nstrings representing the words in the text - A string representing the target word to check frequency for
Your program should:
- Create a
std::map<std::string, int>namedwordCount - Read the number of words
- For each word, read it and update its count in the map using the square bracket operator and increment
- Read the target word to check
- Print the frequency of the target word using the format shown below
Use the following exact output format:
The word "[target_word]" appears [frequency] timesIf the target word doesn't exist in the map, accessing it with the square bracket operator will automatically create an entry with a count of 0, so you can safely print the frequency without checking if the word exists first. Use wordCount[word]++ to increment the count for each word as you read it - this will create new entries with count 1 for new words, or increment existing counts for words already seen.
Try it yourself
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
// Read the number of words
int n;
cin >> n;
// Create the map to store word frequencies
map<string, int> wordCount;
// TODO: Write your code here
// Read n words and update their counts in the map
// Then read the target word and output its frequency
return 0;
}All lessons in Logic & Flow
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice4Maps (Key-Value Pairs)
Introducing std::mapCreating a MapAccessing and Modifying ValuesChecking for KeysRemoving PairsIterating Over a MapRecap - Word Frequency2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items