Step 2: Counting the Words Using a HashMap
Why a HashMap?
A HashMap provides an efficient way to store key-value pairs. In our case, the word will be the key, and its frequency will be the value. This will enable us to look up the frequency of a word in constant time.
How to Count?
We'll initialize an empty HashMap (or an object in JavaScript, or a dictionary in Python) to store the occurrences of each word. Let's call this HashMap occurrences
.
Code Snippet for Counting
Here's how you can populate the occurrences
HashMap:
1std::map<std::string, int> occurrences;
2for(auto& word : split_s) {
3 if(occurrences.count(word) > 0) {
4 occurrences[word]++;
5 } else {
6 occurrences[word] = 1;
7 }
8}