问题描述
我正在尝试使用以下代码(使用 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 >Taccumulate0
定义,它是一个整数.所以使用上面的行或
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;
参考资料
- http://en.cppreference.com/w/cpp/algorithm/accumulate立>
- http://www.cplusplus.com/reference/std/numeric/accumulate/
这篇关于使用 std::accumulate 计算平均值失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!