gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:47:01 32 4
gpt4 key购买 nike

我有一个 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com