compute mean using std::accumulate fails

点点圈 提交于 2019-12-08 17:30:31

问题


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?


回答1:


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/


来源:https://stackoverflow.com/questions/9599552/compute-mean-using-stdaccumulate-fails

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!