double mean_array(double *array)
{
double sum = 0.0;
for(int i=0; i<sizeof(array); i++)
sum += array[i];
return sum / sizeof(array);
}
However, it does not work. It seems it is incompatible with the array definition. Maybe some other problems. Could someone please tell me how to correct it?
Thanks in advance.
That function wouldn't even have worked on a normal array because array in mean_array is a pointer and sizeof(array) gives you the size of the pointer. There is no way you can calculate the size of the array from just the pointer. Normally such functions takes the size of the array as an extra argument.
1 2 3 4 5 6 7
double mean_array(double *array, std::size_t size)
{
double sum = 0.0;
for(int i=0; i < size; i++)
sum += array[i];
return sum / size;
}
To use this function on myArray you can use the data() member function to get a pointer to the first element in the array and the size() member function to get the number of elements in the array. mean_array(myArray.data(), mean_array.size());
You can also change the function to take the std::array<double, 100> object directly.
1 2 3 4 5 6 7
double mean_array(const std::array<double, 100>& array)
{
double sum = 0.0;
for(int i=0; i<array.size(); i++)
sum += array[i];
return sum / array.size();
}
Actually the function is a bit more complicated. I have to determine the size of array depending on another constant int. Declare and initiate the array:
1 2 3
constint time = 100;
array<double, time> myArray = {};
myArray.fill(1.0);
In this case, if I use your second proposition (which asks only one argument), double mean_array(const std::array<double, time>& array) won't work. How should I write the argument to the function, please?
and I think what we do here is just to build a function to calculate the average of an array declared with array class. Is it possible to build a function that can calculate the average of array no matter its type, please?
Actually the size of arrays are known in advance. I use constint time = 100; to make it easier to adjust the size (there are a lot of arrays in my code).
I tried with the function with template. During compiling, the compiler (MSVS) said
"error LNK2019: unresolved external symbol "double __cdecl mean<class std::array<double,100> >(class std::array<double,100> const &)" (??$mean@V?$array@N$0GE@@std@@@@YANABV?$array@N$0GE@@std@@@Z) referenced in function _main"
Could it be a small problem somewhere? Maybe it is from auto value : container ?
Thanks in advance.