2014-04-28 16 views
2

我無法找到一種方法來添加一部分向量int。例如,如果我的向量int [89,49,28,73,93,62,74,26,57,23等]查找向量的一部分的總和int

如何將向量添加到3組中? (89 + 49 + 28),(73 + 93 + 62),(74 + 26 + 57)

或5組? (89 + 49 + 28 + 73 + 93),(62 + 74 + 26 + 57 + 23)

基本上,然後把這些數字加入另一個矢量。

例1:的組3 --->矢量和= [166228157,...]

例2:的組2 --->向量總和= [138101155,...]

+1

好了,你張貼到目前爲止,我們可以幫助你找出什麼地方錯了代碼。 – Mat

+2

你可以使用'std :: accumulate'。 – chris

+0

我如何能夠積累我的情況?我已經閱讀了www.cplusplus.com上的累積參考頁面,我仍然感到困惑。抱歉。我對此仍然陌生。 – user3579946

回答

0

您可以使用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沒有通過矢量的結束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