It must be the most common function for what everyone has a code snippet somewhere, but I have actually spent no less than 1.5 hour searching for it on SO as well as on other C++ sites and have not found a solution.
I would like to calculate the mean of a double array[] using a function. I would like to pass the array to the function as a reference. There are millions of examples where the mean is calculated in a main() loop, but what I am looking for is a function what I can put in an external file and use it any time later.
So far, here is my latest version, what gives a compile error:
double mean_array( double array[] )
{
int count = sizeof( array ) / sizeof( array[0] );
double sum = accumulate( array, array + count, 0 );
return ( double ) sum / count;
}
The compile error is:
error C3861: ‘accumulate’: identifier not found
Can you tell me how to fix this function? What does that compile error mean?
If I use std::accumulate (over the already defined using namespace std), then I get the following error:
'accumulate' : is not a member of 'std'
'accumulate': identifier not found
Why is ‘accumulate’ not a member of ‘std’?
p.s.: I know I can do ‘sum += array[i]’ way and not use accumulate, but I would like to understand what is happening here and how can I make my example work.
Try to add
It will bring in the ‘std::accumulate’ function you’re looking for.
Going further, you’re gonna have a problem to find out the number of elements in your array. Indeed, an array cannot be passed to a function in the hope that the function will be able to know the size of the array. It will decay to a pointer. Therefore, your
countcalculation will be wrong. If you want to be able to pass an actual size specified array, you have to use a templated function.