I am getting compilation error is following code. I thought this should have worked in c++
Can anybody help me to understand what is wrong here.
template < typename elem_type>
elem_type *find2( std::vector<elem_type>& vec, elem_type value) {
for ( int i = 0; i < vec.size(); ++i) {
if ( vec[i] == value ) {
return &vec[i];
}
}
return 0;
}
int main( int argc, char **argv) {
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
std::vector<int> vec( arr, arr+10);
int value = 9;
int *ptr1 = find2(vec,value);
}
following is the compilation error
1> d:\personal\work\find\find\find.cpp(25) : see reference to function template instantiation 'elem_type *find2<int>(std::vector<_Ty> &,elem_type &)' being compiled
1> with
1> [
1> elem_type=int,
1> _Ty=int
1> ]
compiler is Visual Studio 11
In this line,
you are comparing the signed
intvariableito the unsignedsize_tresult ofvec.size().The compiler warns because such a comparision is unsafe in the face of implicit promotions in C++.
iis promoted tosize_t. Ifiwere (hypothetically) negative, that would produce a really huge value, and would thus produce an unexpected comparision result.A simple cure is to
and then do e.g.
You will probably get at least one answer recommending the apparently simpler
but this is problematic for the same reason that the compiler warned: using unsigned integers as numbers risks getting very weird and unexpected results, buggy results, due to implicit promotions and in general conversion from negative number to unsigned, or vice versa.
Even better than the casting above, define a
countOffunction likeand then write just
And best, forget about that indexing and use iterators: