element-wise multiplication of two vectors in c++

c++

Solution

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.

Problem

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?

Original source