vector<int> nums={1,12,-5,-6,50,3};
int k=4;
int n=nums.size();
for(int i=0;i<=n-k;i++)
cout<<accumulate(nums.begin()+i,nums.begin()+i+k-1,0)<<" ";
The output of the above code is: 8 1 39
The question is why sum of [1,12,-5,-6] is 8, which should be 2=(1+12-5-6) ?
Same for 1, which should be 51=(50+12-5-6), and
Same for 39, which should be 42=(50+3-6-5)?
If your hypothesis is that
std::accumulate
doesn't treat negative numbers in the conventional way, then test it directlyThe output is 2, corresponding to
1 + 12 - 5 - 6
.The issue is in your code; and in your iterator addition. Specifically, the first two parameters of
std::accumulate
are both relative tonums.begin()
: you need to drop the-1
from the second parameter.