views:

185

answers:

4

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

+5  A: 

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)

Chris Jester-Young
Valarrays are the correct solution IMO. With luck, your implementation uses SSE instructions to implement the procedure, making it significantly faster. See http://www.pixelglow.com/macstl/valarray/ for one such implementation of valarray. Unfortunately, its not very widespread, so if you want the advantages of SSE instructions you'll probably have to use compiler intrinsics...
Dragontamer5788
@Dragon: `valarray` is the best STL solution, but it's not very good for high-performance computing because it tends to copy data in memory a lot, and produces sequences of small loops containing single operations which have poor memory access patterns. It is easier to upgrade from `valarray` to a proper expression template system, though.
Potatoswatter
+9  A: 

Yes, using std::transform:

std::transform(myv1.begin(), myv1.end(), myv1.begin(),
               std::bind1st(std::multiplies<T>(),3));
Oli Charlesworth
Thanks alot that's genius !!
ismail marmoush
A: 

Hi. Just : if you can have your data in a fixed size array (float values[N]) you could use SSE intrinsics to make it faster as it will multiply sevreral float a a time (4).

dzada
A: 

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<typename _ITStart, typename _ITEnd, typename _Func , typename _Value >
_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.

slashmais
This works, but is essentially reinventing the wheel, as `std::transform` already does this for you.
Oli Charlesworth
Yes - saw in the accepted answer ... but do you realize what pleasure it is to reinvent a wheel that actually works ;) Anyway I'll shoot myself the day I become a conformist ;)
slashmais