The standard STL vector container has a "reserve" function to reserve uninitialized memory that can be used later to prevent reallocations.
How come that the other deque container hasn't it?
Deque can have additional memory overhead over vector because it's made of a few blocks instead of contiguous one.
Elements in a deque are not contiguous in memory; vector elements are guaranteed to be. So if you need to interact with a plain C library that needs contiguous arrays, or if you care (a lot) about spatial locality, then you might prefer vector .
The deque is a bit slower than the vector, that is logical because here there are more cache misses due to the segmented parts.
Vector provides good performance while insertion and deletion at end only and bad performance for insertion and deletion at middle. Deque provides same kind of performance as vector for insertion & deletion at end and middle. Apart from that deque provides good performance for insertion and deletion at front also.
Increasing the size of a std::vector
can be costly. When a vector
outgrows its reserved space, the entire contents of the vector must be copied (or moved) to a larger reserve.
It is specifically because std::vector resizing can be costly that vector::reserve()
exists. reserve()
can prepare a std::vector
to anticipate reaching a certain size without exceeding its capacity.
Conversely, a deque
can always add more memory without needing to relocate the existing elements. If a std::deque
could reserve()
memory, there would be little to no noticeable benefit.
For vector
and string
, reserved space prevents later insertions at the end (up to the capacity) from invalidating iterators and references to earlier elements, by ensuring that elements don't need to be copied/moved. This relocation may also be costly.
With deque
and list
, earlier references are never invalidated by insertions at the end, and elements aren't moved, so the need to reserve capacity does not arise.
You might think that with vector
and string
, reserving space also guarantees that later insertions will not throw an exception (unless a constructor throws), since there's no need to allocate memory. You might think that the same guarantee would be useful for other sequences, and hence deque::reserve
would have a possible use. There is in fact no such guarantee for vector
and string
, although in most (all?) implementations it's true. So this is not the intended purpose of reserve
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With