Multiply vector elements by a scalar value using STL

Ismail Marmoush picture Ismail Marmoush · Oct 7, 2010 · Viewed 65.4k times · Source

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 }?

Answer

Oliver Charlesworth picture Oliver Charlesworth · Oct 7, 2010

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>