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



我在这里看到了对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;
}

最新更新