Suppose I have a vector and I want to size it somehow, but I don't want to initialize values. This website says that the "resize" method of vector will value-initialize upon resize, but I don't know what that means. Does it mean these two are essentially equivalent:
1 2 3 4 5 6
std::vector<double> myvec;
myvec.resize(bignum); // 1
double * myarr = newdouble[bignum]; // 2
// I know that 2 doesn't do any iterating through individual elements; does 1?
Obviously the reserve function is cheaper than initialising them all to 0.0, but what about the second one? aren't both the first two functions simply allocating some space and not doing anything to it?
> I want to access it later using the [] operator.
Therefore, you need to resize()
> but what about the second one?
myvec.resize(100); value initializes the new elements; it is logically equivalent to myvec.resize(100,0.0);
This is a fundamental requirement; or else it can result in undefined behaviour. For instance in: auto n = std::count_if( myvec.begin(), myvec.end(), []( double d ) { return d > 100.0 ; } );
I disagree that it's a fundamental requirement though, they decided to do it for garbage collection to avoid accessing undefined elements. But it creates a performance issue and hinders the push for using vectors over arrays in c++, because in this instance an array is superior and materially faster unless you rewrite the code to check for size and resize as needed (which is obfuscated).
Anyway I'll go with the vector until I profile but I suspect this will become an issue.
You will see that the allocation of memory doubles each time you add an element
It's compiler specific. I recently checked the capacity each time the vector became full, one compiler doubled the current capacity, another used a factor of 1.5.
I assume there could well be other algorithms too.