I need a vector with n elements inside(I mean the size not the capacity of the vector is n) but don’t want to initialize any of them during creation because that’s nothing but rubbish to me. Is there any efficient way to achieve this?
Edit: All I can imagine is to use reserve(n) and do some hack(can somebody tell me how) to make the vector believe it has n elements. Or I just jump into a cesspit and dance with malloc and free.
When you construct a vector with the constructor taking a
sizeparameter (and don’t specify an element to copy into the vector), the elements will be value-initialized. The rules for value initialization (8.5p7) specify that primitives are zero-initialized.The only way round this is to wrap your primitive in a class type that defines a no-op default constructor:
If you can encapsulate the initialization process as an iterator, you could use the iterator to construct the vector:
Otherwise I’d recommend not worrying too much about the overhead of initialization; it’s not going to change the complexity of your algorithm (since you’ll be accessing each member anyway, which makes it O(n) already).