Search code examples
c++stlvectorelementoperation

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


Solution

  • 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>