So everything runs perfectly except when i try to search for a value inside of the array, it keeps telling me that the value wasn't found despite the fact that it is in the array.
#include <iostream>
usingnamespace std;
template<typename T>
T Search_Array(T[],T,T);
int main()
{
int size;
cout<<"Enter the size of the array: ";
cin>>size;
int* pArray = newint[size];
for ( int i = 0 ; i < size ; ++i )
{
cout<<"Enter the value of the element with index " <<i<<" : ";
cin>>pArray[i];
}
cout<<"\nYour Array: \n";
for ( int i = 0 ; i < size ; ++i )
{
cout<<pArray[i]<<" ";
}
int Search_Result;
int User_Input;
cout<<"\nEnter a number you would like to search for: \n";
cin>>User_Input;
Search_Result = Search_Array(pArray, size , User_Input);
if ( Search_Result >= 0 )
{
cout<<"The number " <<User_Input<< " was found with index " <<Search_Result<<endl;
}
else
{
cout<<"The number " <<User_Input<< " was not found\n";
}
system("pause");
return 0;
}
template<typename T>
T Search_Array(T a[], T s, T i)
{
for ( int i = 0 ; i < s ; ++i )
{
if ( i == a[i] )
{
return i;
}
}
return -1;
}
i'm still pretty new to templates.
Your help is appreciated, Thank you.
You're creating two variables called i in your Search_Array function, one is an argument of type T T Search_Array(T a[], T s, T i)<-The one on the end here, the other is an int for ( int i = 0 ; i < s ; ++i ).
Change the name of the first i to something else (you will also need to change the first i in if ( i == a[i] ) to the same name)
Also, the function should return a bool (true if found, false if not), at the moment if the first element turns out to be the one you're looking for then the function will return 0, which you have given the meaning of "not found"
template<typename T>
T Search_Array(T a[], T s, T i)
{
for ( int i = 0 ; i < s ; ++i )
{
if ( i == a[i] )
{
return i;
}
}
return -1;
}
It's not guaranteed that type T is always going to have an equal or lesser numeric limit than an integer.
Therefore, I would change line 4 from this snippet to: for ( T i = 0 ; i < s ; ++i )
In conjunction with renaming it as Lachlan suggested.