📖 Scenario: You are working in a bookstore. You have a list of books sold today. You want to count how many copies of each book were sold.
🎯 Goal: Build a program that counts the frequency of each book sold using a hash map (dictionary) and prints the result.
📋 What You'll Learn
Create a vector of strings called books_sold with the exact book titles given.
Create an empty unordered_map called frequency to count book sales.
Use a for loop with variable book to iterate over books_sold and update frequency.
Print the frequency of each book in the format: Book Title: count.
💡 Why This Matters
🌍 Real World
Counting how many times each item appears is useful in sales analysis, inventory management, and data summarization.
💼 Career
Frequency counting with hash maps is a common technique in software development, data analysis, and coding interviews.
Progress0 / 4 steps
1
Create the list of books sold
Create a vector of strings called books_sold with these exact entries: "Harry Potter", "The Hobbit", "Harry Potter", "Game of Thrones", "The Hobbit", "Harry Potter".
DSA C++
Hint
Use std::vector<std::string> and initialize it with the exact book titles inside curly braces.
2
Create the frequency map
Add an empty unordered_map called frequency that maps std::string to int to count how many times each book appears.
DSA C++
Hint
Include <unordered_map> and declare frequency as std::unordered_map<std::string, int>.
3
Count the frequency of each book
Use a for loop with variable book to iterate over books_sold and increase the count in frequency[book] by 1 for each book.
DSA C++
Hint
Use a range-based for loop and increment frequency[book] inside the loop.
4
Print the frequency of each book
Use a for loop with variables book and count to iterate over frequency and print each book and its count in the format: Book Title: count.
DSA C++
Hint
Use a range-based for loop with structured bindings to print each book and its count.
Practice
(1/5)
1. What is the main purpose of using a hash map in the Frequency Counter Pattern?
easy
A. To reverse the order of elements
B. To sort the elements in ascending order
C. To store elements without any duplicates
D. To count how many times each element appears in a collection
Solution
Step 1: Understand the role of a hash map
A hash map stores key-value pairs, allowing quick lookup and update of counts.
Step 2: Apply to frequency counting
We use the hash map keys as elements and values as their counts to track frequency.
Final Answer:
To count how many times each element appears in a collection -> Option D