searching array of a template type

Hello everyone,

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)(((long unsigned int)i) * 32)))))’ from ‘std::__cxx11::basic_string<char>’ to ‘boolif (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;
}
Last edited on
On line 7, you wrote value = array[i], but meant value == array[i].
Last edited on
I fixed that but it doesnt seem to find the name i passed in
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
using namespace std;
or to qualify all entities from the standard library with
std::
Then we can try it out in C++ shell.
Last edited on
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 ...
Last edited on
1
2
3
4
5
6
7
8
template <typename InputIterator, typename T> 
InputIterator searchFor(InputIterator begin, InputIterator end, T const& t) {
  for ( ; begin != end; ++begin) 
    if (*begin == t) 
      return begin;

  return end;
}


In the standard library, this function is called std::find.
Last edited on
Registered users can post here. Sign in or register to post.