Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector element-wise product with C++ and STL

Tags:

c++

stl

It is not difficult to implement element-wise product in C++:

vector<float> a_array;
vector<float> b_array;
vector<float> c_array;
vector<float> dot_array;
....
for(int i=0; i<a_array.size(); i++)
{
   float temp;
   temp = a_array[i]*b_array[i]*c_array[i];
   dot_array[i] = temp;
}

This is a very simple implementation, and I am wondering whether there are more efficient algorithms already available in STL. Thanks!

like image 417
feelfree Avatar asked Dec 01 '22 21:12

feelfree


2 Answers

std::transform can be used to multiply two vectors:

#include <algorithm>
#include <functional>

// Precondition: b.size() >= a.size() && r.size() >= a.size()
std::transform(a.begin(), a.end(), b.begin(), r.begin(), std::multiplies<float>());

There is no similar standard algorithm with more than two input sequences.

like image 112
Mike Seymour Avatar answered Dec 04 '22 10:12

Mike Seymour


Have a look at std::inner_product.

Edit I posted this answer when the question was about dot product. For element-wise product, see the second version of std::transform.

like image 37
juanchopanza Avatar answered Dec 04 '22 10:12

juanchopanza