std::accumulate(v.begin(), v.end(), 0) is run on a vector of doubles. What does it return, and why?
Correct answer
B. int, because the accumulator takes the type of the initial value given
14 views
B. int, because the accumulator takes the type of the initial value given
14 views
std::accumulate declares its accumulator with the type of the third argument, so passing the literal 0 accumulates in int and truncates every fractional part. Pass 0.0 or a value-initialised element type to accumulate in the range's own type. The trap is expecting the result type to follow the iterator's value type, as a fold expression or std::reduce would.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is B? Ask here and get an explanation.