Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compute mean using std::accumulate fails

Tags:

c++

std

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?

like image 435
moooeeeep Avatar asked Mar 07 '12 10:03

moooeeeep


1 Answers

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

  • http://en.cppreference.com/w/cpp/algorithm/accumulate
  • http://www.cplusplus.com/reference/std/numeric/accumulate/
like image 184
Zeta Avatar answered Sep 30 '22 14:09

Zeta