C ++向量累加 [英] C++ vector accumulates
本文介绍了C ++向量累加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用向量的累加函数
I was trying to use the accumulate function for vectors
vector <double> A;
double B = 0;
A.reserve(100);
for(itr = 0; itr < 210; itr++)
{
term1 = pow(r[itr], 12);
term1 = 1/term1;
term2 = pow(r[itr], 6);
term2 = 2/term2;
A.push_back(term1 - term2);
}
B = accumulate(A.begin(), A.end(), 0);
但是,我总是B = 0,而A有非零值
however, I always got B = 0, while A had nonzero values
推荐答案
std :: accumulate
是一个有点鬼祟的意思,结果的类型是类型的初始值,并且不是容器元素的类型!所以你的累加器产生 int
s。
std::accumulate
is a bit sneaky in the sense that the type of the result is the type of the initial value, and not the type of the container elements! So your accumulator produces int
s.
/ code>:
accumulate(A.begin(), A.end(), 0.0);
// ^^^^^^^ literal of type double
这篇关于C ++向量累加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文