Wawel100
Wawel100

Reputation: 1271

Perform vector operation

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!

Upvotes: 2

Views: 7860

Answers (5)

Michael J
Michael J

Reputation: 7929

Consider using an std::valarray as it is a more appropriate choice.

There is a reason why the standard library provides a wide variety of containers. It permits the developer to use "horses for courses".

The std::vector is the simplest container and as such is the best choice for many cases. However for specific cases, the added functionality of another container type may make that type a better choice. This may be one such case, where the numerical manipulation of the array members is better handled by the std::valarray.

Upvotes: 1

GManNickG
GManNickG

Reputation: 503755

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.

Upvotes: 10

Peter G.
Peter G.

Reputation: 15114

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.

Upvotes: 1

Logan Capaldo
Logan Capaldo

Reputation: 40336

You can use std::transform:

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

Upvotes: 1

ufukgun
ufukgun

Reputation: 7209

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.

Upvotes: 0

Related Questions