I have this project for C++ programming and I was wondering if anyone could help
ID: 3725435 • Letter: I
Question
I have this project for C++ programming and I was wondering if anyone could help point me in the right direction. Not sure what a template-based function is or how I can count occurences if I don't know the type.
Write a template-based function frequency that will return the count of the occurrences of an item in an array of items. 1. Test the template with the types int, double, and string. 2. The program will NOT prompt for any data. A sample call to frequency with the type char: char CArray[] "this is a sample line of text". coutExplanation / Answer
#include<iostream>
using namespace std;
// template function to return the frequence of x in arr
template<class T>
int frequency(T arr[], int len, T x);
int main()
{
int arr1[] = { 1, 2, 4, 1, 5, 1, 6, 1 };
cout<<"Frequency of 1 : "<<frequency<int>(arr1, 8, 1);
return 0;
}
// template function to return the frequence of x in arr
template<class T>
int frequency(T arr[], int len, T x)
{
int count = 0;
int i;
// traverse through the array
for( i = 0 ; i < len ; i++ )
// if the crrent element is same as x
if( arr[i] == x )
count++;
return count;
}