0

Suppose the vector I have is <1, 2, 3>, I want to get the accumulated values vector <1, 3, 6>. I guess that the C++ function partial_sum do that. But this function does not work when I execute (program bug). Is it partial_sum used correctly ?

vector<float> vv, vvSum;
vv.push_back(1); vv.push_back(2); vv.push_back(3);

partial_sum(vv.begin(), vv.end(), vvSum.begin(), plus<float>());

for(unsigned int i = 0; i < vvSum.size(); ++i)
{
    cout << vv[i] << " " << endl;
}

1 Answer 1

3

No, partial_sum is being used incorrectly.

The vvSum vector is empty. In that situation, vvSum.begin() is an end iterator, and thus cannot be used for output.

You can call vvSum.resize(vv.size()); to make it have the same size as the original, or use a std::back_inserter(vvSum) iterator, which increases the size of the container as needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.