7

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?

Zeta
  • 103,620
  • 13
  • 194
  • 236
moooeeeep
  • 31,622
  • 22
  • 98
  • 187

1 Answers1

14

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;

References

Zeta
  • 103,620
  • 13
  • 194
  • 236
  • 12
    Or just pass the initial value as `0.0`. I’d prefer that: less code. – Konrad Rudolph Mar 07 '12 at 10:29
  • @KonradRudolph: Thanks, just noticed that myself and updated my answer. – Zeta Mar 07 '12 at 10:30
  • 1
    @NeilKirk: The question was edited, probably to provide a compiling example. However, the error was fixed at the same time. Reproduced the original scenario in the question. – Zeta Jul 23 '14 at 13:03