Initialize double array with nonzero values (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 pa开发者_如何学编程ckage, 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).
You always use memset()
if you don't want to loop.
That is, memset(myarr, 5, arrsize);
in order to fill it with all 5's. Beware of implicit conversion to unsigned char.
SYNOPSIS
#include <string.h> void * memset(void *b, int c, size_t len);
DESCRIPTION
The memset() function writes len bytes of value c (converted to an unsigned char) to the byte string b.
And if the vector is large, and you need it to go fast and you are using gcc, then :
Code generation of block move (memcpy) and block set (memset) was rewritten. GCC can now pick the best algorithm (loop, unrolled loop, instruction with rep prefix or a library call) based on the size of the block being copied and the CPU being optimized for.
精彩评论