Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract a value from each element of a std::vector

Tags:

c++

vector

I have a vector like std::vector<float> myVector. I have to subtract a float value from each of its elements. Using a for loop is very inefficient, as my vector is very large (5000+). I tried:

transform(myVector.begin(), myVector.end(), myVector.begin(), bind2nd(std::minus<float>(), valuesToRemove[0]));

Where valuesToRemove is a float array. But this does not change my original vector.

How do I do this in the correct way?

like image 758
harsh Avatar asked Jan 29 '18 23:01

harsh


1 Answers

but it does not change my original vector. How do I do that in the correct way?

std::transform is for mapping a function over one range, and outputting into another range. std::for_each is an in-place analogue, that you could use.

Using a for loop is very inefficient as my vector is very long (5000+)

Loop is the most efficient way to repeat an operation on a very long vector (on a (super)scalar processor).

I recommend following:

for(auto& element : myVector)
    element -= valuesToRemove[0];

Your loop may benefit from vector operations (SIMD). Make sure to let compiler tune for those if possible. If the compiler fails to vectorise the loop, you can explicitly unroll the iterations to expedite their use. If that fails, you could try using compiler intrinsics to vectorise manually at the expense of platform independence.

If your vector is long enough, and the process is repeated enough, then you might benefit from using a vector processor. Many desktop systems contain one in the form of a GPU. Modern GPU's provide an API to perform general vector calculations.

like image 119
eerorika Avatar answered Nov 29 '22 22:11

eerorika