c++ - 使用 std::accumulate,得到 "too many arguments"错误

标签 c++ accumulate

std::accumulate 应该能够接受三个或四个参数。在前一种情况下,它只是您想要将数字添加到容器中的时候;在后一种情况下,您需要先应用一个函数,然后再添加它们。我编写了生成随机 double vector 的代码,然后对它们做了一些事情:首先它使用 std::transform 执行 x->x^2 转换,然后将它们与 std::accumulate,最后使用 std::accumulate 的四参数版本将两个 Action 合二为一。

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

关于c++ - 使用 std::accumulate,得到 "too many arguments"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14430117/

相关文章:

c++ - 如何降低排序的时间复杂度?

python - 在 Qt C++ 应用程序中创建 python 解释器小部件的简单方法?

c++ - C++堆栈变量的销毁顺序是否有任何保证

c++ - 用迭代器计算矩阵 vector<vector<double>> 的列和?

c++ - 高效积累

c++ - 二进制和文本模式编写的文件之间的区别

c++ - 有没有办法让 CreateProcess 创建的进程在另一个窗口中打开?

c++ - C++尝试使用max和累加函数

c++ - 为什么 std::accumulate 在 C++20 中没有被设为 constexpr?

C编程: Sum of a sequence of integers until zero and prints the sum of two multiplied integers