I'm trying to compute the mean value of a vector of doubles using the following code (compiled with g++ mean.cc -std=c++0x
):
// mean.cc
#include <algorithm>
#include <iostream>
#include <vector>
struct Mean {
unsigned int n;
Mean(unsigned int n) : n(n) {}
double operator()(double sum, double x) {
return sum + x/n;
}
};
int main () {
std::vector<double> v = {1,2,3,4,5,6};
Mean mean(v.size());
std::cout << "mean: " << std::accumulate(v.begin(), v.end(), 0, mean) << "\n";
return 0;
}
The mean value should be 3.5
, I think. The program however prints mean: 1
.
If I remove the division by n
in my operator()
the sum of the elements is computed as expected. What am I doing wrong here?
It seems that gcc uses accumulate<vector<double>::iterator,int>
instead of accumulate<vector<double>::iterator,double>
. If you use the specific template values it will work:
cout << "mean: " << accumulate<vector<double>::iterator,double>(v.begin(), v.end(), 0, mean) << endl;
EDIT: This happens because the type T
in template< class InputIterator, class T >
T accumulate
is defined by your initial value 0
, which is an integer. So use the line above or
cout << "mean: " << accumulate(v.begin(), v.end(), 0.0, mean) << endl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With