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

标签 c++

我有一个 double vector ,我想通过乘以 double 来转换它。我想使用 std::transform,但我无法解决它。我将如何设置一个函数来使用下面的“因子”将初始 vector 转换为结果 vector ?

这是我的代码的表示:

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)

谢谢。

最佳答案

至少有三种不同的方法可以做到这一点,包括:

  • 自定义仿函数类
  • 兰巴实例
  • 绑定(bind)二元仿函数

请参阅下面的所有三个:

#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以及完全手动循环的实现,因为这些似乎不是您要找的。

祝你好运。

关于c++ - 设置二进制函数以使用转换时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32241046/

相关文章:

c++ - 这些叫什么

c# - new 关键字在 C# 中的工作原理

c++ - 如何警告 C 中 void 指针参数的类型不兼容?

c++ - 我可以拥有非拥有的共享指针吗?

C++ 使用模板来避免编译器检查 boolean 值

c# 与 c++ ssl_connect

c++ - glm : is not a type or namespace? 我的标题中有令人困惑的错误

c++ - 限制 header 中变量的范围

c++ - 从 C++ 列表中删除实体的差异

c++ - 如何按照标准迭代枚举?