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?