设置二进制函数以使用转换时出现问题

Problems setting up binary function to use transform

我有一个双精度向量,我想通过乘以双精度来转换它。我想使用 std::transform,但我无法解决它。我将如何设置函数以使用下面的 "factor" 将初始向量转换为结果向量?

这是我的代码的表示:

double a, b, factor;
std::vector<double> init;
std::vector<double> result;



// Code that initializes a, b, and 
// fills in InitVec with timeseries (type double) data

factor = a/b;
result.resize(init.size())
std::transform(init.begin(), init.end(), result.begin(), /*function that multiplies init by factor*/)

是不是很简单:

std::transform(init.begin(), init.end(), result.begin(), *factor)

谢谢。

你需要一个函数来获得一个 double 和 returns 一个新的 double.
你也需要在这个函数中获得因素。
使用 lambda 表达式很容易:

std::transform(init.begin(), init.end(), result.begin(),  
    [factor](double val) -> double { return val*factor; }
);

为了更好地理解它,它是以下代码的简短版本,除了 factor 可以在函数中使用,即使它只是调用 transform 的局部变量:

double modify(double val)
{
    return val*factor;
}
...
std::transform(init.begin(), init.end(), result.begin(), modify);

即。 lambda 表达式是作为其他内容的一部分内联编写的未命名函数,它也可以 "capture" 来自其调用者上下文的局部变量。

您至少可以通过三种不同的方式执行此操作,包括:

  • 自定义函子class
  • lamba 实例
  • 绑定二元函子

所有三个见下文:

#include <iostream>
#include <algorithm>
#include <vector>

struct mult_by
{
    double val;
    mult_by(double v) : val(v) {}
    double operator()(double arg) { return arg * val; };
};

int main()
{
    using namespace std::placeholders;
    double a = 1, b = 2, factor = a/b;

    std::vector<double> init;
    std::vector<double> result;

    init.emplace_back(1.0);
    init.emplace_back(2.0);

    // using a functor
    std::transform(init.begin(), init.end(), std::back_inserter(result), mult_by(factor));

    // using a lambda
    std::transform(init.begin(), init.end(), std::back_inserter(result),
                   [factor](double d){ return d * factor; });

    // binding to a standard binary-op (std::multiplies)
    std::transform(init.begin(), init.end(), std::back_inserter(result),
                   std::bind(std::multiplies<double>(), _1, factor));

    // should report three pairs of 0.5 and 1
    for (auto x : result)
        std::cout << x << '\n';
}

您选择哪个取决于偏好或编译器限制。就我个人而言,我会发现后者令人反感,但只是因为它是可能的,所以将其作为一种选择提出。我故意遗漏了 std::for_each 和完全手动循环的实现,因为这些似乎不是您要找的。

祝你好运。