Multiply vector elements by a scalar value using STL

后端 未结 5 1091
刺人心
刺人心 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:20

    I know this not STL as you want, but it is something you can adapt as different needs arise.

    Below is a template you can use to calculate; 'func' would be the function you want to do: multiply, add, and so on; 'parm' is the second parameter to the 'func'. You can easily extend this to take different func's with more parms of varied types.

    template
    _ITStart xform(_ITStart its, _ITEnd ite, _Func func, _Value parm)
    {
        while (its != ite) { *its = func(*its, parm); its++; }
        return its;
    }
    ...
    
    int mul(int a, int b) { return a*b; }
    
    vector< int > v;
    
    xform(v.begin(), v.end(), mul, 3); /* will multiply each element of v by 3 */
    

    Also, this is not a 'safe' function, you must do type/value-checking etc. before you use it.

提交回复
热议问题