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
#include <iostream>
#include <vector>
#include <iomanip>
#include <string.h>
#include <string>
#include <algorithm>//USE C++14
using namespace std;
bool stringiEq(const string& a, const string& b)
{
//check each characters by case insensitive
return std::equal(a.begin(), a.end(),
b.begin(), b.end(),
[](char a, char b) {
return tolower(a) == tolower(b);
});
}
unsigned GetWordFrequency(vector<string>&vs,const string&str)
{
//return the number of occurrences of the search word in the
//vector parameter (case insensitive).
unsigned ans=0;//the numbers of occurences
for(auto it:vs)
{
if(stringiEq(it,str))
ans++;
}
return ans;
}
int main()
{
int size=0;
cin>>size;
vector<string>vs;
for(int i=0;i<size;i++)
{
string s;
cin>>s;
vs.push_back(s);
}
for(auto it:vs)
{
cout<<setw(20)<<it<<" -> "<<GetWordFrequency(vs,it)<<endl;
}
cout<<"----------------END-----------------\n";
return 0;
}
Comments
Leave a comment