I'm trying to search an item in an array of the same type in the function searchFor using templates. When i compile it i get this error and don't understand why:
1 2 3 4
main.cpp: In instantiation of ‘int searchFor(T, T*) [with T = std::__cxx11::basic_string<char>]’:
main.cpp:15:29: required from here
main.cpp:7:3: error: could not convert ‘value.std::__cxx11::basic_string<char>::operator=((*(const std::__cxx11::basic_string<char>*)(array + ((sizetype)(((longunsignedint)i) * 32)))))’ from ‘std::__cxx11::basic_string<char>’ to ‘bool’
if (value = array[i]) return i;
Here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <string>
template <class T>
int searchFor(T value, T array[]){
for(int i = 0; i < 5; ++i){
if (value = array[i]) return i;
}
}
int main(){
string array[] = {"Levi", "Dane", "Jovanie", "Tyler", "Kassirer"};
string name = "Tyler";
while(searchFor(name, array) != -1){
std::cout << "Value of searchFor: " << array[searchFor(name, array)] << endl;
}
return 0;
}
searchFor() won't return anything if the name is not in the array.
searchFor() will never return the value of -1 that you ask for on line 15. Put return -1;
after line 8.
Actually, I should remove that while loop altogether: at present (after correcting other errors) it will return 3 every time and the while loop will run indefinitely!
Please ensure that you post compileable code. To get this to compile you either need to have usingnamespace std;
or to qualify all entities from the standard library with std::
Then we can try it out in C++ shell.
by the way: you "assume" that the array has 5 elements in searchFor(...), did you consider using a proper container, like std::vector or std::array ? it's only advantageous to use them, they know their size, and std::vector can be resized ...