Are these effectively doing the same thing?
vector<MyType> stuff;
MyClass(MyType *things, int numThings){
for (int i = 0; i < numThings; ++i){
//stuff[i] = things[i]; //original version of question, fixed
stuff.push_back(things[i]);
}
}
vs.
vector<MyType> stuff;
MyClass(MyType *things, int numThings) : stuff(things, things+numThings) {}//fixed
If they are, any more or less overhead using either approach? (except for the additional typing in method 1)
No.
The first method crashes, since it accesses elements beyond the end of the zero-size vector. If this bug is fixed by resizing the vector first, elements in the vector will first be initialized, and then be overwritten using
operator=. If instead the bug is fixed by usingpush_back()in the loop, then vector may be resized during the loop.The second method initializes the vector with the desired contents in one step, it is to be preferred since this is simpler and obviously correct. It also does not have the overhead of resizing the vector, and does not have the overhead of initializing elements twice.
Edit: Looks like the second one is also a bug:
should be
I can never remember all of the constructors for standard library classes, funny how
stringhas this constructor butvectordoesn’t.Fixed versions
The following two versions are roughly equivalent: