C++: Allocate memory for an std::vector then initialize its elements in parallel
Your options are:
- Replace
std::vector
with an alternative (e.g. uvector) - Use some sort of library to resize without initialization, such as UninitializedMemoryHacks from Facebook.
After you've performed the resize, you can use OpenMP in the usual ways.
It depends on the default constructor for your type U. If the default constructor is cheap, it is very unlikely that you will gain anything parallelizing it.
struct U {
int a, b, c;
U():a(0), b(1), c(2) {}
};
If your default constructor is expensive, it would make more sense to split it in two parts: One for default initialization and a function for the actual initialization.
struct U {
vector<int> a;
U() {}
void init(int n) { a.resize(n); }
};
In both alternatives, the regular resize or assign call to the vector would be very hard to beat.
If you really are set in doing things this way, you could use a reinterpret_cast to an array. This way, the default constructor won't be called.
U * u_array = reinterpret_cast<U*>(malloc(100*sizeof(U)));
I strongly advise against this last option.