C++向量累加
我试图对向量使用累积函数
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 具有非零值
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);
however, I always got B = 0, while A had nonzero values
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
std::accumulate
有点狡猾,因为结果的类型是初始值的类型,而不是容器元素的类型!所以你的累加器会产生int
。要解决此问题,请累积为
double
: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 producesint
s.To fix this, accumulate into a
double
:关键可能是你正在做什么[...] //将值填充到A中
`
向量A
双 B = 0;
则解析 B = 3.0
如果在保留之后执行 a[0] = 1,
这是糟糕的代码。
你可能想做的是调整大小。
Reserve 只为您提供后备内存容量,它实际上并没有创建有效的迭代器。所以 A.begin() 仍然等于 A.end()
查看代码更改,您知道整数和双精度数学之间的区别吗?
第 1 项和第 2 项是积分吗?
the key may be how your are doing [...] //Fill values into A
`
vector A
double B = 0;
resolves B = 3.0
if after the reserve you are doing a[0] = 1
this is bad code.
what you might want to do instead is say resize.
reserve only gives you the backing memory capacity, it doesn't actually create the valid iterators.. so A.begin() still equals A.end()
looking at code change, do you know the difference between integer and double math?
are term1 and term 2 integral?