You forgot to return from the function in this case
find(v, value, n - 1);
Nevertheless the function in any case is defined incorrectly.
It should look like
template <class T>
bool find( const std::vector<T> &v, const T &value, typename std::vector<T>::size_type n )
{
return v.size() < n || n == 0 ? false : v[n-1] == value || find( v, value, n - 1 );
}
Here is a demonstrative program.
#include <iostream>
#include <iomanip>
#include <vector>
template <class T>
bool find( const std::vector<T> &v, const T &value, typename std::vector<T>::size_type n )
{
return v.size() < n || n == 0 ? false : v[n-1] == value || find( v, value, n - 1 );
}
int main()
{
std::vector<int> v = { 1, 2, 3, 4, 5 };
std::cout << std::boolalpha << find( v, 5, v.size() ) << '\n';
std::cout << std::boolalpha << find( v, 5, v.size() - 1 ) << '\n';
std::cout << std::boolalpha << find( v, 1, 1 ) << '\n';
std::cout << std::boolalpha << find( v, 2, 1 ) << '\n';
return 0;
}
Its output is
true
false
true
false
As for your function implementation then it will have undefined behavior for example for this call
find( v, 5, v.size() )
due to using an invalid index equal to v.size() in this if statement
if (v[n] == value) {
cout << v[n] << " == " << value << endl;
return true;
}
Actually the user can specify the third argument greater than the size of the array. So a more flexible approach is to allow the user ti specify any value for the third argument but perform the search among existent elements of the vector. Here is such a function definition.
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
template <class T>
bool find( const std::vector<T> &v, const T &value, typename std::vector<T>::size_type n )
{
n = std::min( n, v.size() );
return n != 0 && ( v[n-1] == value || find( v, value, n - 1 ) );
}
int main()
{
std::vector<int> v = { 1, 2, 3, 4, 5 };
std::cout << std::boolalpha << find( v, 5, 6 ) << '\n';
std::cout << std::boolalpha << find( v, 5, 4 ) << '\n';
return 0;
}
The program output is
true
false
n==0norv[n] == value?return, your function never looks atv[0], and so will never find the value if it happens to be in the first element. Recall that the first three elements arev[0],v[1]andv[2]; but notv[3].std::findshould be used.