Multiply vector elements by a scalar value using STL

后端 未结 5 1098
刺人心
刺人心 2020-12-23 14:03

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

5条回答
  •  星月不相逢
    2020-12-23 14:17

    Yes, using std::transform:

    std::transform(myv1.begin(), myv1.end(), myv1.begin(),
                   std::bind(std::multiplies(), 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(), 3));
    

    For the placeholders;

    #include  
    

提交回复
热议问题