Finding the sum a portion of vector int

Hello everyone. I am having trouble finding a way to add a portion of a vector int. For example, if my vector int is [89, 49, 28, 73, 93, 62, 74, 26, 57, 23, etc...]

How would add the vector in groups of 3? (89+49+28),(73+93+62),(74+26+57)
Or groups of 5? (89+49+28+73+93),(62+74+26+57+23)
Basically groups of i.

And then putting the sums into another vector.
Example1: Groups of 3 ---> vector<int> sum = [166,228,157,...]
Example2: Groups of 2 ---> vector<int> sum = [138,101,155,...]
anyone?
Just take them in groups of three.

1
2
3
4
5
6
7
8
// precondition: make sure that xs.size() is a multiple of 3
for (size_t n = 0; n < xs.size(); n += 3)
  {
  int x0 = xs[ n + 0 ];
  int x1 = xs[ n + 1 ];
  int x2 = xs[ n + 2 ];
  //do something with x0,x1,x2 here
  }

There are other, prettier ways of doing this, but this best explains the basic concept.

Hope this helps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <algorithm>
#include <iostream>
#include <vector>

std::vector<int> sum(int groups, const std::vector<int> &v) {
    std::vector<int> s;
    size_t beg = 0;
    const int g = groups;
    
    for (size_t len = v.size(); groups < len; groups += g) {
        s.push_back(std::accumulate(v.begin() + beg, v.begin() + groups, 0));
        beg = groups;
    }
    
    if (beg < v.size())
        s.push_back(std::accumulate(v.begin() + beg, v.end(), 0));
    return s;
}


Demo: http://coliru.stacked-crooked.com/a/d0a1d88693491840
Topic archived. No new replies allowed.