使用std :: accumulate,得到"太多参数"错误

lim*_*imp 2 c++ accumulate

std::accumulate应该能够采取三个或四个参数.在前一种情况下,只是当你想在容器中添加数字时; 在后一种情况下,当你想先应用一个函数然后添加它们时.我已经编写了生成随机双精度矢量的代码,然后对它们做了一些事情:首先它使用x-> x ^ 2变换std::transform,然后将它们相加std::accumulate,最后将这两个动作组合成一个使用四个-argument版本std::accumulate.

一切都有效,除了第3步.查看http://www.cplusplus.com/reference/numeric/accumulate/上的示例代码,我看不出为什么这不起作用的原因,但我'在编译时得到"太多的参数错误"(我正在使用XCode.由于某种原因,它没有告诉我行号,但我已将其缩小到第二次使用std::accumulate).任何见解?

#include <numeric>
#include <time.h>
#include <math.h>
using std::vector;
using std::cout;
using std::endl;

double square(double a) {
    return a*a;
}

void problem_2_1() {
    vector<double> original;

    //GENERATE RANDOM VALUES
    srand((int)time(NULL));//seed the rand function to time
    for (int i=0; i<10; ++i) {
        double rand_val = (rand() % 100)/10.0;
        original.push_back(rand_val);
        cout << rand_val << endl;
    }

    //USING TRANSFORM        
    vector<double> squared;
    squared.resize(original.size());

    std::transform(original.begin(), original.end(), squared.begin(), square);

    for (int i=0; i<original.size(); ++i) {
        std::cout << original[i] << '\t' << squared[i] << std::endl;
    }


    //USING ACCUMULATE
    double squaredLength = std::accumulate(squared.begin(), squared.end(), 0.0);
    double length = sqrt(squaredLength);
    cout << "Magnitude of the vector is: " << length << endl;

    //USING 4-VARIABLE ACCUMULATE
    double alt_squaredLength = std::accumulate(original.begin(), original.end(), 0.0, square);
    double alt_length = sqrt(alt_squaredLength);
    cout << "Magnitude of the vector is: " << alt_length << endl;
}
Run Code Online (Sandbox Code Playgroud)

jua*_*nza 8

std :: accumulate重载的第四个参数需要是二元运算符.目前你正在使用一元一个.

std::accumulate在容器中的连续元素之间执行二进制操作,因此需要二元运算符.第四个参数替换默认的二进制操作,add.它不应用一元操作然后执行添加.如果你想对元素进行平方然后添加它们,你需要类似的东西

double addSquare(double a, double b)
{
  return a + b*b;
}
Run Code Online (Sandbox Code Playgroud)

然后

double x = std::accumulate(original.begin(), original.end(), 0.0, addSquare);
Run Code Online (Sandbox Code Playgroud)