gpt4 book ai didi

c++ - 使用 std::accumulate 计算均值失败

转载 作者:可可西里 更新时间:2023-11-01 18:19:06 26 4
gpt4 key购买 nike

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

// 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

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

最佳答案

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

cout << "mean: " << accumulate<vector<double>::iterator,double>(v.begin(), v.end(), 0, mean) << endl;

编辑:发生这种情况是因为类型 Ttemplate< class InputIterator, class T >
T accumulate
由您的初始值定义 0 , 这是一个整数。所以使用上面的行或者

cout << "mean: " << accumulate(v.begin(), v.end(), 0.0, mean) << endl;

引用资料

关于c++ - 使用 std::accumulate 计算均值失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9599552/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com