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

时间:2013-01-20 22:37:03

标签: c++ accumulate

std::accumulate应该可以采用三个或四个参数。在前一种情况下,只是当你想在容器中添加数字时;在后一种情况下,当你想先应用一个函数然后添加它们时。我编写了生成随机双精度矢量的代码,然后对它们做了一些事情:首先使用std::transform执行x-> x ^ 2变换,然后将它们与std::accumulate相加,最后使用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;
}

1 个答案:

答案 0 :(得分:8)

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

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

这样的东西
double addSquare(double a, double b)
{
  return a + b*b;
}

然后

double x = std::accumulate(original.begin(), original.end(), 0.0, addSquare);