我找不到添加 vector int 的一部分的方法。例如,如果我的 vector int 是 [89, 49, 28, 73, 93, 62, 74, 26, 57, 23, etc...]
如何以 3 个为一组添加 vector ? (89+49+28),(73+93+62),(74+26+57)
还是 5 人一组? (89+49+28+73+93),(62+74+26+57+23)
基本上是 i 组。然后将总和放入另一个 vector 。
示例 1:3 人一组 ---> vector 和 = [166,228,157,...]
示例 2:2 人一组 ---> vector 和 = [138,101,155,...]
最佳答案
您可以使用 std::accumulate
, 喜欢关注
// 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 ;
在这里,你需要确保 it
没有通过 vector v
的结尾你可以这样做来附加零,像这样:
int zeros = n - (( v.size( ) % n ) ? ( v.size( ) % n ) : n ) ;
for( int x = 1 ; x <= zeros; ++x )
v.push_back( 0 );
您最终可以将上面的 for 循环与 std::accumulate
演示 here
关于c++ - 求 vector int 的一部分的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23332767/