26.5k views
0 votes
"Write a generic C++ function" that takes an array of generic elements and a scalar of the same type as the array elements. The type of the array elements and the scalar is the generic parameter. The function must search the given array for the given scalar and return the subscript of the scalar in the array. If the scalar is not in the array, the function must return –1. Test the function for int and float types.

User Sebanti
by
5.2k points

1 Answer

0 votes

Answer:

#include<iostream>

using namespace std;

template <class myType>

int generic(myType *a, myType b)

{

int i;

for(i=0;a[i]!=-1;i++)

{

if( b == a[i])

return i;

}

return -1;

}

int main()

{

int a[]={1,2,3,4,5,6,7,8,-1};

float b[]={1.1,2.1,3.1,4.1 ,5.1,6.1,7.1,-1};

if(generic(a,5)>0)

{

cout<<" 5 is foundin int at index "<<generic(a,5)<<endl;

}

else

{

cout<<" 5 notfound "<<endl;

}

if(generic(b,(float)5.1)>0)

{

cout<<" 5.1 isfound in float at index "<<generic(a,5)<<endl;

}

else

{

cout<<" 5.1 notfound "<<endl;

}

system("pause");

}

/*

sample output

5 is found in int at index 4

5.1 is found in float at index 4

*/

User Fabianius
by
3.9k points