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"
You are dereferencing the
end
iterator, which is undefined behavior.C++ ranges are, by convention, specified by a pair of iterators where the left iterator points to the first item, and the right iterator points one past the last item. This allows a range to be empty, by having
begin == end
.Your base cases should be:
Then, pass
mid
to both halves of the recursion, because it will be included in the second half (where it is the left iterator), and excluded in the first half (where it is the end iterator).v.end()
is not a dereferencable iterator. It represents "one past the end".This will work.