我使用std :: accumulate和测试代码获得意外结果。我试图添加一个大的双向量,但由于某种原因,值溢出:
#include <iostream>
#include <vector>
#include <functional>
#include <numeric>
using namespace std;
double sum(double x, double y)
{
// slows things down but shows the problem:
//cout << x << " + " << y << endl;
return (x+y);
}
double mean(const vector<double> & vec)
{
double result = 0.0;
// works:
//vector<double>::const_iterator it;
//for (it = vec.begin(); it != vec.end(); ++it){
// result += (*it);
//}
// broken:
result = accumulate(vec.begin(), vec.end(), 0, sum);
result /= vec.size();
return result;
}
int main(int argc, char ** argv)
{
const unsigned int num_pts = 100000;
vector<double> vec(num_pts, 0.0);
for (unsigned int i = 0; i < num_pts; ++i){
vec[i] = (double)i;
}
cout << "mean = " << mean(vec) << endl;
return 0;
}
总和里面的cout的部分输出:
2.14739e + 09 + 65535
2.14745e + 09 + 65536
-2.14748e + 09 + 65537
-2.14742e + 09 + 65538
-2.14735e + 09 + 65539
正确输出(迭代):
mean = 49999.5
输出不正确(使用累积):
mean = 7049.5
我可能犯了一个累了的错误?我之前已成功使用累积...
由于
答案 0 :(得分:9)
您需要将double
传递给accumulate
:
result = accumulate(vec.begin(), vec.end(), 0.0, sum);
^^^
否则使用int
执行累积,然后将结果转换为double。