I have a little wondering what the third element "0" stands for in the accumulate function.

std::vector<double> vec(10);

double sum = std::accumulate( vec.begin() + 1, vec.begin() + 5, 0);

I have a problem with this std::accumulate function. When compiling this I have quite much compile notifications but it compiles.
One that says:

warning C4244: '=' : conversion from 'double' to 'int', possible loss of data

This is what is happening here. I have declared the elements in vector "vec" to doubles with 2 decimals.
However the output of this will be 15 wich is an integer. The output should have been.
(10,50 + 20,50 / 2) = 15,50.

I wonder what I could be doing wrong since everything is declared to doubles. Where is the conversion from double to int that seems to be happening.

#include <numeric>

std::vector<double> vec(12);

vec[1] = 10.50;
vec[2] = 20.50;

double sum = std::accumulate( vec.begin() + 1, vec.begin() + 3, 0);
double Average = ( sum / (3 - 1)  );
			
ofstream out;
out.open("C:\\test.txt");

out << Average;

I changed the third argument "0" to a double literal so I wrote 0.0 wich worked great.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.