C++ Program to Count Words that Appear Exactly Two Times in an Array of Word In this program, we will write a C++ code that will take an array of words as input and count the number of words that appear exactly two times. This program will be implemented using a hash map data structure. The hash map will store the frequency of each word in the input array and based on that, we will count the number of words that appear exactly two times.
Here is the code for the C++ program:
#include<bits/stdc++.h> using namespace std; unordered_map<string, int> frequency; void countWords(string arr[], int n) { for (int i=0; i<n; i++) frequency[arr[i]]++; int count = 0; for (auto x : frequency) if (x.second == 2) count++; cout << "Number of words appearing exactly " << "twice: " << count << endl; } int main() { string arr[] = {"one", "two", "three", "one"}; int n = sizeof(arr)/sizeof(arr[0]); countWords(arr, n); return 0; }
Explanation of the code:
First, we have included the header file bits/stdc++.h
that includes all the necessary libraries required for this program.
We have declared an unordered map frequency
that will store the frequency of each word in the input array.
In the function countWords
, we have taken an input array arr
and the size of the array n
as parameters.
The for loop inside the countWords
function iterates through the input array and counts the frequency of each word using the hash map frequency
.
The second for loop iterates through the frequency
hash map and checks if the frequency of a word is equal to 2. If it is, the count
variable is incremented.
The final result, which is the number of words appearing exactly twice, is displayed using the cout
statement.
In the main
function, we have defined an input array of words and passed it to the countWords
function along with its size.
This is the complete code for counting the number of words appearing exactly two times in an array of words using the hash map data structure in C++.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.