Reputation: 31
Simple enough, I am trying to define a recursive method to return the medium of a vector. However, my code didn't work, the compiler doesn't complain anything but the program just terminated at the point when the function was called. I tried to look through the code again and again. Any help would be greatly appreciated :D
int minR(vector<int> vec, size_t start){
if(start == vec.size()-1){return vec[start];}
int temp = minR(vec, start++);
return ((vec[start] < temp) ? vec[start] : temp);
}
Upvotes: 1
Views: 340
Reputation: 53037
int temp = minR(vec, start++);
should be this:
int temp = minR(vec, start + 1);
The postfix ++
increments the value and "returns" the previous value, which is essentially calling the function with the same value of start
.
Upvotes: 2
Reputation: 21863
In this line
int temp = minR(vec, start++);
You are calling minR(vec, start)
and not minR(vec, start+1)
as you think you are. This causes an infinite recursion and that's why your program stops.
You should call
int temp = minR(vec, start + 1);
Upvotes: 2