I am trying to extract the maximum element in a vector in c++ using recursion with only one parameter in the function:
int maxR(vector<int> v) {
if (v.size() != 1) {
if (v[v.size()-1] > v[v.size()-2]) {
v[v.size()-2] = v[v.size()-1];
v.pop_back();
/*check what happens to v during recursion: cout << v[v.size()-1] <<endl;*/
return maxR(v);
}
else {
v.pop_back();
return maxR(v);
}
return v[0];
}
}
int main() {
vector<int> v = { 3,16,2,4,7,11,19 };
cout << maxR(v);
}
So I was hoping it would return the number 19, but for some reasons, it return me a zero i.e 0.
So I added the line:
cout << v[v.size()-1] <<endl;
to see what is happening during recursion, and I got this: 19 19 19 19 19 19 0
So I am not sure what is wrong with my code?
could someone points out the error?