Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ vector accumulates

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

like image 943
Josh Avatar asked Nov 22 '11 13:11

Josh


2 Answers

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
like image 192
Kerrek SB Avatar answered Oct 22 '22 00:10

Kerrek SB


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?

like image 2
Dan Avatar answered Oct 22 '22 01:10

Dan