I would like to create a vector of some complex type, by reading individual elements from a stream. I know the vector size in advance. Is it better to specify the number of elements in the vector constructor or by using reserve method? Which one of these two is better?
int myElementCount = stream.ReadInt(); vector<MyElement> myVector(myElementCount); for (int i = 0; i < myElementCount; i++) { myVector[i] = stream.ReadMyElement(); } or
int myElementCount = stream.ReadInt(); vector<MyElement> myVector; myVector.reserve(myElementCount); for (int i = 0; i < myElementCount; i++) { myVector.push_back(stream.ReadMyElement()); } What about the case where I just create a vector of ints or some other simple type.
resize()instead ofreserve(), it's a common confusion for newbs.resizealso default construct the objects? OP is doing thepush_backanyway. Maybe I'm confused too :)