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.
You could use std::fill
(#include <algorithm>
):
std::fill(v.begin(), v.end(), 1);
This is essentially also only a loop of course..
'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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With