hyp*_*not 8 c++ arrays stl std visual-studio-2010
它必须是每个人在某个地方都有代码片段的最常见功能,但实际上我花了不少于1.5小时在SO和其他C++站点上搜索它并且没有找到解决方案.
我想计算double array[]
使用函数的平均值.我想将数组作为参考传递给函数.有数百万个例子,其中均值是在main()循环中计算的,但我正在寻找的是一个函数,我可以放入外部文件并在以后的任何时候使用它.
到目前为止,这是我的最新版本,是什么给出了编译错误:
double mean_array( double array[] )
{
int count = sizeof( array ) / sizeof( array[0] );
double sum = accumulate( array, array + count, 0 );
return ( double ) sum / count;
}
Run Code Online (Sandbox Code Playgroud)
编译错误是:
错误C3861:'accumulate':找不到标识符
你能告诉我如何修复这个功能吗?编译错误是什么意思?
如果我使用std::accumulate
(超过已定义的using namespace std
),则会出现以下错误:
'accumulate' : is not a member of 'std'
'accumulate': identifier not found
Run Code Online (Sandbox Code Playgroud)
为什么'积累'不是'std'的成员?
ps:我知道我可以做'sum + = array [i]'方式而不是使用累积,但我想了解这里发生了什么,我怎样才能让我的例子有效.
Did*_*set 24
尝试添加
#include <numeric>
Run Code Online (Sandbox Code Playgroud)
它将引入您正在寻找的'std :: accumulate'功能.
更进一步,你将有一个问题,找出你的数组中的元素数量.实际上,数组不能传递给函数,希望函数能够知道数组的大小.它将衰减为指针.因此,您的count
计算将是错误的.如果您希望能够传递指定数组的实际大小,则必须使用模板化函数.
template <int N>
double mean_array( double ( & array )[N] )
{
return std::accumulate( array, array + N, 0.0) / (double)(N);
}
Run Code Online (Sandbox Code Playgroud)