C ++中两个向量的元素乘法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13728430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
element-wise multiplication of two vectors in c++
提问by Dnaiel
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 循环(使用推回)更有效的(单行)方法在 c++ 中(按元素)乘以两个向量。我目前的做法如下,
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?
有什么建议?
回答by David Rodríguez - dribeas
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.
您可以替换v.begin()
为std::back_inserter(v)
如果v
为空,您应该reserve()
预先存储以避免多次分配。
回答by David Stone
You could look into std::valarray. It's designed to allow mathematical operations on every element in the array.
您可以查看std::valarray。它旨在允许对数组中的每个元素进行数学运算。