Search code examples
c++vectoraccumulate

using accumulate to sum 12 numbers at a time from one vector and then adding the result to another vector C++


I am wanting to sum 12 numbers at a time(to simulate a year) then adding the results to a separate vector but I seem to be struggling. I have tried to get 12 numbers at a time into a loop but I'm unsure. Here is a sample from the text file i'm reading.


Solution

  • You have to accumulate the value for each year, which means for 12 consecutive elements in your input vector.
    Each time you hit the 12th elements, your accumulator has the expected value.

    double currentrain = 0;
    for(int i = 0; i < rainfall.size(); ++i) {
        // accumulate rain this year
        currentrain += rainfall[i];
        // i%12==11 on december
        if((i%12)!=11)
            continue;
        // we have accounted each month in this year
        sum.push_back(currentrain);
        // reset the accumulator for next year
        currentrain = 0;
    }