122k views
3 votes
Word frequencies - functions

Define a function named GetWordFrequency that takes a vector of strings and a search word as parameters. Function GetWordFrequency() then returns the number of occurrences of the search word in the vector parameter (case insensitive).
Then, write a main program that reads a list of words into a vector, calls function GetWordFrequency() repeatedly, and outputs the words in the vector with their frequencies. The input begins with an integer indicating the number of words that follow.
Ex: If the input is:
5 hey Hi Mark hi mark
the output is:
hey 1
Hi 2
Mark 2
hi 2
mark 2
Hint: Use tolower() to set the first letter of each word to lowercase before comparing.
The program must define and use the following function:
int GetWordFrequency(vector wordsList, string currWord)
#include
#include
#include
#include
using namespace std;
/* Define your function here */
int main() {
/* Type your code here */
return 0;
}

User Fmt
by
4.5k points

1 Answer

4 votes

Answer:

#include <iostream>

#include <vector>

#include <iomanip>

#include <string.h>

#include <string>

#include <algorithm>

using namespace std;

bool strEqual(const string& str1, const string& str2)

{

//check each characters by case insensitive

return std::equal(str1.begin(), str1.end(),

str2.begin(), str2.end(),

[](char str1, char str2) {

return tolower(str1) == tolower(str2);

});

}

unsigned GetWordFrequency(vector<string>& vec,const string& str)

{

//return the number of occurrences of the search word in the

unsigned res=0;//the numbers of occurences

for(auto itr:vec)

{

if(strEqual(itr,str))

res++;

}

return res;

}

int main()

{

int size=0;

cin>>size;

vector<string>vec;

for(int i=0;i<size;i++)

{

string str;

cin>>str;

vec.push_back(str);

}

cout<<"Output:"<<endl;

for(auto itr: vec)

{

cout<<itr<<" - "<<GetWordFrequency(vec,itr)<<endl;

}

return 0;

}

Step-by-step explanation:

User ANIK ISLAM SHOJIB
by
4.1k points