C++向量累加

发布于 2024-12-17 16:31:23 字数 342 浏览 4 评论 0原文

我试图对向量使用累积函数

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

森林散布 2024-12-24 16:31:23

std::accumulate 有点狡猾,因为结果的类型是初始值的类型,而不是容器元素的类型!所以你的累加器会产生int

要解决此问题,请累积为 double

accumulate(A.begin(), A.end(), 0.0);
//                             ^^^^^^^ literal of type 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 produces ints.

To fix this, accumulate into a double:

accumulate(A.begin(), A.end(), 0.0);
//                             ^^^^^^^ literal of type double
无妨# 2024-12-24 16:31:23

关键可能是你正在做什么[...] //将值填充到A中
`
向量A
双 B = 0;

A.reserve(100);
A.push_back(1);
A.push_back(2);
B = accumulate(A.begin(), A.end(), 0);
return 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;

A.reserve(100);
A.push_back(1);
A.push_back(2);
B = accumulate(A.begin(), A.end(), 0);
return 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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文