tags:

views:

167

answers:

5

Hi,

I'm using the vector container to store an array of doubles. Is there any quick way of multiplying each element in my vector by some scalar without using a loop.

For example:

  vector<double> Array(10,1);

will initialise an array of 10 doubles with initial value 1. To multiply this array by 0.5 I would write:

  for(unsigned int i=0; i<Array.size(); i++) 
     Array[i] = 0.5*Array[i]; 

Is there there another way? I have used valarray which overloads the '*' operator so that:

     Array = 0.5 * Array; 

is valid but I'd rather not use valarray as it seems the vector container is a more standard approach for manipulating arrays.

Thanks!

A: 

as i know there is not.

if there is one, probably it encapsulates this loop for you. so i dont think the performance would change.

ufukgun
+7  A: 

You could do this:

std::transform(Array.begin(), Array.end(), Array.begin(),
                std::bind2nd(std::multiplies<double>(), 0.5));

In response to getting the sum of elements:

double sum = std::accumulate(Array.begin(), Array.end(), 0.0);

And in response to getting sqrt'ing each element:

std::transform(Array.begin(), Array.end(), Array.begin(),
                static_cast<double (*)(double)>(std::sqrt));

That cast is to select the correct overload.

GMan
Thanks, I assume there a function to get the sum of the elements in a vector?
Wawel100
@Wawel100: Yup, I've added it. If you found an answer solved your problem, click the check mark on it.
GMan
Thanks! Just one final question: how would I use transform to get the sqrt root of each element?
Wawel100
+1  A: 

You can use std::transform:

 std::transform(Array.begin(), Array.end(), Array.begin(), std::bind1st(std::multiplies<double>(), 0.5)));
Logan Capaldo
wouldn't that be a loop hidden by stl?
sum1stolemyname
Of course. What do you think valarray does?
Logan Capaldo
+1  A: 

The STL vector itself does not allow elementwise scaling in a single operation.

You could wrap your vector with a decorator which applys a scaling factor. The application of a new factor would be O(1) regardless of the size of the vector. This is comes not for free as the drawbacks are increased complexity and a somewhat larger access per element.

Peter G.
A: 

Consider using an std::valarray.

Michael J
Well he did say in the question he'd rather not. :)
GMan