C++ vector accumulates

陌路散爱 提交于 2019-12-20 20:02:16

问题


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


回答1:


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



回答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?



来源:https://stackoverflow.com/questions/8227610/c-vector-accumulates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!