c ++中两个向量的元素级乘法 [英] element-wise multiplication of two vectors in c++
问题描述
我试图用两个向量进行以下数学运算:
v1 = [a1] [a2] [a3 ] [a4] [a5]
v2 = [b1] [b2] [b3] [b4] b5]
b $ b
想计算:
v = [a2 * b2] [a3 * b3] [a4 * b4 ] [a5 * b5]
注意,我不想使用新向量中的第一个元素。 / p>
我想知道是否有一个更有效的(单线程)方式在c ++中乘以(元素方式)两个向量而不是for循环(使用推回) 。我目前的方法如下,
for(long i = 1; i v.push_back(v1 [i] * v2 [i]);
}
我也尝试了以下操作,
for(long i = 1; i v [i-1] = v1 [i] * v2 [i];
}
有任何建议吗?
std :: transform(v1.begin()+ 1,v1.end(),
v2.begin 1,v.begin(),//假定v1,v2的大小大于1,
// v一个元素小于
std :: multiplies< int>()); //假设值为'int'
可以替换 v.begin )
与 std :: back_inserter(v )
如果 v
为空,您应该 reserve()
以避免多次分配。
I am trying to do the following mathematical operation with two vectors:
v1 = [a1][a2][a3][a4][a5]
v2 = [b1][b2][b3][b4]b5]
Want to compute:
v = [a2*b2][a3*b3][a4*b4][a5*b5]
Note that I did not want the first element in the new vector.
I was wondering if there is a more efficient (one-liner) way to multiply (element-wise) two vectors in c++ than a for-loop (using push back). My current approach is as follows,
for(long i=1;i < v1.size();++i){
v.push_back(v1[i]*v2[i]);
}
I also tried the following,
for (long i = 1; i < v1.size(); ++i){
v[i-1] = v1[i]*v2[i];
}
Any suggestions?
std::transform( v1.begin()+1, v1.end(),
v2.begin()+1, v.begin(), // assumes v1,v2 of same size > 1,
// v one element smaller
std::multiplies<int>() ); // assumes values are 'int'
You can replace v.begin()
with std::back_inserter(v)
if v
is empty, you should reserve()
memory upfront to avoid multiple allocations.
这篇关于c ++中两个向量的元素级乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!