I have a very large multidimensional vector that changes in size all the time. Is there any point to use the vector.reserve() function when I only know a good approximation
If you know the size of a vector at construction time, pass the size to the c'tor and assign using operator[]
instead of push_back
. If you're not totally sure about the final size, make a guess (maybe add a little bit more) and use reserve
to have the vector reserve enough memory upfront.
What would be the negative/positive sides of reserving the maximum size my vector can have which would be [256*256][50][256] in some cases.
Negative side: potential waste of memory. Positive side: less CPU time, less heap fragmentation. It's a memory/cpu tradeoff, the optimum choice depends on your application. If you're not memory-bound (on most consumer machines there's more than enough RAM), consider reserving upfront.
To decide how much memory to reserve, look at the average memory consumption, not at the peak (reserving 256*256*50*256 is not a good idea unless such dimensions are needed regularly)