C++ vector accumulates

2019-03-19 08:11发布

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

2条回答
疯言疯语
2楼-- · 2019-03-19 08:42

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?

查看更多
劳资没心,怎么记你
3楼-- · 2019-03-19 08:43

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
查看更多
登录 后发表回答