使用 std::transform_reduce 计算复杂表达式

问题描述 投票:0回答:1

我有以下内容:

std::vector<double> Coefficients;
std::vector<double> Functions;
std::vector<std::vector<double>> Polynomials;

给定一些输入

std::vector<double> X
我想评估以下
c1 * f1((x1^p1) * (x2^p2) * ...) + c2 * f2(...
,其中c
Coefficients
中的值,f
Functions
中的值,p
Polynomials
中的值。

举个例子:

Coefficients = {2, -4};
Functions = {sin, cos};
Polynomials = {{4, 3}, {2, 5}};

必须计算:

2 * sin(x1^4 * x2^3) - 4 * cos(x1^2 * x2^5)

我发现了

std::transform_reduce
,它看起来很棒,因为我可以在一行中有效地完成整个事情,但由于我必须执行的封装操作的数量,我无法找出正确的方法。有人可以帮我解决吗?

我在想类似的事情:

std::transform_reduce(
                    std::execution::par,
                    Coefficients.begin(), Coefficients.end(), Functions.begin(), 0.0,
                    std::plus<>(),
                    [&](double c, auto f) {
                        return c * f(std::transform_reduce(  // <-- transform reduce again for the polynomial inside the function and then again for (x^p)? 
c++ c++17
1个回答
0
投票

如果不使用

ranges
,您必须为多项式向量创建一个迭代器,并手动将其推进到外部
transform_reduce

#include <execution>
#include <cmath>
#include <numeric>
#include <vector>

int main()
{
    using std::vector;
    using std::begin, std::end;

    vector vx = {  42.,  69. };
    vector vc = {   2.,  -4. };
    vector vf = { &sin, &cos };
    vector<vector<double>> vvp = { {4., 3.}, {2., 5.} };

    auto vpi = begin(vvp);
    auto res = std::transform_reduce(
        std::execution::par,
        begin(vc), end(vc),
        begin(vf), 
        0.,
        std::plus(),
        [&](double c, auto f)
        {
            auto vp = *vpi++;
            return std::transform_reduce(
                std::execution::par,
                begin(vx),
                end(vx),
                begin(vp),
                0,
                &pow,
                std::multiplies()
            );
        }
    );
}
© www.soinside.com 2019 - 2024. All rights reserved.