使用 std::累积,得到一个"too many arguments"错误

using std::accumulate, getting a "too many arguments" error

本文关键字:一个 too many 错误 arguments 累积 std 使用      更新时间:2023-10-16

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;
}

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);