如何在 C++ 中获得 2 个向量的加权和?

How do I get weighted sum of 2 vectors in C++?

我看到 post 求和 2 个向量。我想做一个加权和。

std::vector<int> a;//looks like this: 2,0,1,5,0
std::vector<int> b;//looks like this: 0,0,1,3,5

我想做 a * 0.25 + b * 0.75 并存储在一些向量中。 我看到了这个函数 std::transform 但想知道如何为它编写自定义操作。

版本 1:使用 std::transform 和 lambda

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

int main()
{ 
    std::vector<int> a{2,0,1,5,0};
    std::vector<int> b{0,0,1,3,5};

    //create a new vector that will contain the resulting values
    std::vector<double> result(a.size());
    std::transform (a.begin(), a.end(), b.begin(), result.begin(), [](int p, int q) -> double { return (p * 0.25) + (q * 0.75); });
    for(double elem: result)
    {
        std::cout<<elem<<std::endl;
    }
    return 0;
}

版本 2:使用免费功能

#include <iostream>
#include <vector>
#include<algorithm>
double weightedSum(int p, int q)
{
    return (p * 0.25) + (q * 0.75);
}
int main()
{ 
    std::vector<int> a{2,0,1,5,0};
    std::vector<int> b{0,0,1,3,5};

    //create a new vector that will contain the resulting values
    std::vector<double> result(a.size());
    std::transform (a.begin(), a.end(), b.begin(), result.begin(), weightedSum);
    for(double elem: result)
    {
        std::cout<<elem<<std::endl;
    }
    return 0;
}

版本 3:使用 std::bind

将权重作为参数传递
#include <iostream>
#include <vector>
#include<algorithm>
#include <functional>

using namespace std::placeholders;
double weightedSum(int p, int q, double weightA, double weightB)
{
    return (p * weightA) + (q * weightB);
}
int main()
{ 
    std::vector<int> a{2,0,1,5,0};
    std::vector<int> b{0,0,1,3,5};

    //create a new vector that will contain the resulting values
    std::vector<double> result(a.size());
    std::transform (a.begin(), a.end(), b.begin(), result.begin(), std::bind(weightedSum, _1, _2, 0.25, 0.75));
    for(double elem: result)
    {
        std::cout<<elem<<std::endl;
    }
    return 0;
}