How to add all vector elements using divide and conquer and iterators?

廉价感情. 提交于 2019-12-13 05:38:39

问题


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"


回答1:


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:

if (left == right) return 0;
if (left + 1 == right) return *left;

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).

int sumVectorRecurse(vector<int>::iterator left, vector<int>::iterator right)
{
    if (left == right) return 0;
    if (left + 1 == right) return *left;
    int midPosition = (right - left)/2;
    vector<int>::iterator mid = left + midPosition;
    return sumVectorRecurse(left, mid) + sumVectorRecurse(mid, right);
}



回答2:


v.end() is not a dereferencable iterator. It represents "one past the end".

This will work.

sumVectorRecurse( v.begin(), v.end() - 1 );


来源:https://stackoverflow.com/questions/28910187/how-to-add-all-vector-elements-using-divide-and-conquer-and-iterators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!