Reputation: 13
I am trying to find the maximum value in a vector using recursion but I keep on getting a segmentation fault. I can't figure out the issue. Does anyone know why?
int find_max(vector<int> integer_array, int i) { //variable i just keeps track of the index starting at 0
if(i == integer_array.size()-1) {
return integer_array[i];
}
return max(integer_array[i], find_max(integer_array, i++));
}
//Example of a call: find_max(vector_array, 0);
UPDATE: I know it's inefficient but this is just for practicing recursion...
Upvotes: 1
Views: 521
Reputation: 330
I am assuming the vector always has elements.
i+1
instead of i++
:return max(integer_array[i], find_max(integer_array, i+1));
.
The problem with i++
is that this form would pass the value i
to find_max
for the second argument, and then increment. So you end up calling either return max(integer_array[i], find_max(integer_array, i))
or return max(integer_array[i+1], find_max(integer_array, i))
, I forgot if the parameters were evaluated in order or not. In either case, it would not finish correctly.
find_max
1st argument:int find_max(const vector<int> &integer_array, int i)
. Otherwise it would copy the integer_array
again and again without needing to modify the content. see reference.
Upvotes: 1