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
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.
To fix this, accumulate into a double
:
accumulate(A.begin(), A.end(), 0.0);
// ^^^^^^^ literal of type double
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With