I needed to write a function that sums up all elements of a vector. Specifications are that it has to be done by recursion and the only parameters input would be iterators. The function should:Divide the vector in half, recurse on the left hand side, recurse on the right hand side, return the sum of both sides. I wrote the code below but I am getting an incorrect answer.
int sumVectorRecurse(vector<int>::iterator left, vector<int>::iterator right)
{
if (left != right){
int midPosition = (right - left)/2;
vector<int>::iterator mid = left + midPosition;
return (sumVectorRecurse(left, mid) + sumVectorRecurse(mid+1, right));
}
else return *left;
}
int main(){
vector<int> v = {1,2,3,4};
cout << endl << "THIS IS QUESTION 4:"<< endl;
cout << sumVectorRecurse(v.begin(), v.end());
}
Update: the output is okay for a vector till {1,2,3,4}
but once I add 5 to it making it {1,2,3,4,5}
the output is "32782"