Which of below code , assuming there is no out of memory can happen, say if it is correct, if it will crash or performs more than one memory allocation?
My understanding is that here reserve() to pre allocate a suitably large memory block to accomodate a given number of the objects. So vector here will always preallocate a memory block using reserve(). In this case, vector holds a value between 0 to 2000. So I think below Code1 wont have any issues as here there are 0 allocations during for loop, hence its correct. I suspect either Code2, Code3 or Code4 might have issues.
Please advise.
also what does [] do? this is just as important because 4) ... needs attention to details.
I dont have much idea on vector as I am new to this.
that is exactly why you need to do this yourself. It is important, vector is one of the most used things in the c++ language. You can study the things you need here: https://www.cplusplus.com/reference/vector/vector/
I suspect either Code2, Code3 or Code4 might have issues.
Well yes, some of them do have issues - but which one(s)? Don't suspect - investigate and understand and then make a statement as to yes or no because...
> if it will crash
In c++ you may never have that guarantee, a lot of runtime errors end in the realm of undefined behaviour instead
if you do get a crash, consider yourself lucky to have an opportunity for debug
I am not able to figure out which among these code performs more than one memory allocation? I dont see any crash while running these codes separately. In Code2 output is 0,
does that mean it went out of memory?
code1 - memory is allocated (but not used) for 2000 items. So before the push_back size is 0 and 2000 elements can be pushed without memory-reallocation. After size is 2000 and all memory is used.
code2 - again memory is allocated (but not used) for 2000 items. So before assignments, size is 0. However the assign assumes that memory is used when it is not. Hence at the end size is still 0 because as far as vector is concerned, nothing has been used. This is also 'bad' code accessing vector memory that hasn't been 'used'.
code3 - memory is allocated for 2000 items and it is marked as 'used'. The size is hence 2000. Push-back starts at the end of 'used' so starts after the existing 2000 elements. Thus 2000 elements are added to the vector after the existing 2000 giving a final of 4000. The 2000 elements added will cause some memory re-allocation.
code4 - memory is allocated for 2000 items and marked as 'used'. The size is hence 2000. The assignments use this 'used' memory so OK. The final size is 2000.
The difference between reserving the space and resizing is that with resizing, you initialize each element twice; once on growing the vector, and again on assignment.