Multiply vector elements by a scalar value using STL

Hi I want to (multiply,add,etc) vector by scalar value for example myv1 * 3 , I know I can do a function with a forloop , but is there a way of doing this using STL function? Something like the {Algorithm.h :: transform function }?


Yes, using std::transform:

std::transform(myv1.begin(), myv1.end(), myv1.begin(),
               std::bind(std::multiplies<T>(), std::placeholders::_1, 3));

Before C++17 you could use std::bind1st(), which was deprecated in C++11.

std::transform(myv1.begin(), myv1.end(), myv1.begin(),
               std::bind1st(std::multiplies<T>(), 3));

For the placeholders;

#include <functional> 

If you can use a valarray instead of a vector, it has builtin operators for doing a scalar multiplication.

v *= 3;

If you have to use a vector, you can indeed use transform to do the job:

transform(v.begin(), v.end(), v.begin(), _1 * 3);

(assuming you have something similar to Boost.Lambda that allows you to easily create anonymous function objects like _1 * 3 :-P)


Mordern C++ solution for your question.

std::vector<double> myarray;
double myconstant{3.3};
std::transform(myarray.begin(), myarray.end(), myarray.begin(), [&myconstant](auto& c){return c*myconstant;});

I think for_each is very apt when you want to traverse a vector and manipulate each element according to some pattern, in this case a simple lambda would suffice:

std::for_each(myv1.begin(), mtv1.end(), [](int &el){el *= 3; });

note that any variable you want to capture for the lambda function to use (say that you e.g. wanted to multiply with some predetermined scalar), goes into the bracket as a reference.