使用 std::accumulate 计算平均值失败 [英] compute mean using std::accumulate fails

查看:43
本文介绍了使用 std::accumulate 计算平均值失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码(使用 g++ mean.cc -std=c++0x 编译)计算双精度向量的平均值:

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;
}

平均值应该是 3.5,我想.然而,程序会打印mean: 1.

The mean value should be 3.5, I think. The program however prints mean: 1.

如果我在我的 operator() 中通过 n 删除除法,元素的总和将按预期计算.我在这里做错了什么?

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?

推荐答案

gcc 好像用了 accumulate::iterator,int> 而不是 accumulate.如果您使用特定的模板值,它将起作用:

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:发生这种情况是因为 template< 中的 T 类型.类 InputIterator,类 T >Taccumulate 由您的初始值 0 定义,它是一个整数.所以使用上面的行或

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;

参考资料

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆