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.
Asked
Active
Viewed 110 times
-1
-
3What exactly is the question here? – Borgleader Mar 02 '15 at 14:04
-
If you look at [`std::accumulate`](http://en.cppreference.com/w/cpp/algorithm/accumulate) it takes a pair of iterators as arguments. And a vector iterator is random access so you can easily do e.g. `myVector.begin() + 12` to get an iterator to the 13:th element of the vector. – Some programmer dude Mar 02 '15 at 14:09
-
@Borgleader How can i add up 12 elements at a time from my rainfall vector and then add the results to a new vector. – louiej15 Mar 02 '15 at 14:12
2 Answers
0
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;
}

birdypme
- 194
- 1
- 12
-
That makes sense now thankyou! Quick question when displaying the result i.e for(int j = 0; j < sum.size(); ++j){ cout << "Total rainfall is: " << sum[j] <
– louiej15 Mar 02 '15 at 14:22 -
@louiej15 you would need some kind of data structure for that, so that instead of storing vectors of doubles, you would store vectors of structs. One struct would hold {int year; int month; double rainmm;} and the other one {int year; double rainmm;}. I'll leave the rest to you, as it is going outside the scope of your original question (and when I say struct I really think class, but that's up to you and the scope of this project). – birdypme Mar 02 '15 at 15:54
0
You could use std::accumulate directly :
vector<double> result;
for (auto it = begin(rainfall); it+12<=rainfall.end(); it+=12)
result.emplace_back(accumulate(it, it+12, 0));

tux3
- 7,171
- 6
- 39
- 51
-
-
@JoachimPileborg Well, I edited it to simply skip the last one if incomplete, it's much simpler now. – tux3 Mar 02 '15 at 14:28