Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize double array with nonzero values (blas)

Tags:

c++

c

blas

I have allocated a big double vector, lets say with 100000 element. At some point in my code, I want to set all elements to a constant, nonzero value. How can I do this without using a for loop over all elements? I am also using the blas package, if it helps.

like image 274
Günter Avatar asked Mar 10 '11 13:03

Günter


2 Answers

You could use std::fill (#include <algorithm>):

std::fill(v.begin(), v.end(), 1);

This is essentially also only a loop of course..

like image 94
coldfix Avatar answered Nov 11 '22 09:11

coldfix


'fill' is right from what you've said.

Be aware that it's also possible to construct a vector full of a specified value:

std::vector<double> vec(100000, 3.14);

So if "at some point" means "immediately after construction", do this instead. Also, it means you can do this:

std::vector<double>(100000, 3.14).swap(vec);

which might be useful if "at some point" means "immediately after changing the size", and you expect/want the vector to be reallocated ("expect" if you're making it bigger than its prior capacity, "want" if you're making it much smaller and want it trimmed to save memory).

like image 3
Steve Jessop Avatar answered Nov 11 '22 09:11

Steve Jessop