Domanda

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 sum = [166,228,157,...]

Example2: Groups of 2 ---> vector sum = [138,101,155,...]

È stato utile?

Soluzione

You can use std::accumulate , like following

// v the original vector
// int n =3; // groups
for(it= v.begin(); it != v.end() ; it += n )
    std::cout << std::accumulate( it, it+n, 0) << std::endl ;

Here, you need to make sure it doesn't pass end of vector v you can do this for appending zeros, something like this :

int zeros = n - (( v.size( ) % n )  ?  ( v.size( ) % n ) : n ) ;
for( int x = 1 ; x <= zeros; ++x )
    v.push_back( 0 );

And the you can finally use the above for loop with std::accumulate

Demo here

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top