开发者

Perform vector operation

开发者 https://www.devze.com 2023-01-08 09:29 出处:网络
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.

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++) 
     Arra开发者_开发百科y[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!


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.


You can use std::transform:

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


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消