I was reading about deque
s vs vector
s, and came across its wikipedia entry, which says one of the three possible implementations of deque
using dynamic arrays is:
Allocating deque contents from the center of the underlying array, and resizing the underlying array when either end is reached. This approach may require more frequent resizings and waste more space, particularly when elements are only inserted at one end.
I was wondering if there are any STL (or STL-style) implementations that actually use this center-allocation strategy?
I am asking because this strategy looks rather appealing as it involves only one underlying array, and thus removes the memory dis-contiguity issue, which is probably the only major issue deque
has when compared to vector
. If I understand it right, this could well be a replacement for std::vector
that allows O(1) pop_front
(amortized) or a replacement for deque
with memory-contiguity guarantees. I assume that this is at the cost of doubling the buffering space of a std::vector
, which is not a major concern for my use cases.
Also, is it true that insertion/deletion in the middle of such a container would take half the time of std::vector
on average?
UPDATE:
As @Lightness Races in Orbit pointed out, such a implementation will not be used under current standards because no one can benefit from the upsides per contract with STL and everyone will suffer from the downsides. A further question I have regarding the downsides is this:
Is it possible to implement a new vector
or deque
like container (say bivector
) such that in addition to the functionality/operators of std::vector
,
1) provides (amortized) constant time push_front()
and pop_front()
operations and
2) guarantees memory contiguity but not iterator validity after growing sizes?
I imagine with one array behind the scene, a lot of the indirection/performance issues on deque
would go away.
No Standard Library (not "STL") implementation is going to bother with this, because it has the downsides you mention, and the upsides are not part of the requirement for std::deque
.
Those requirements are carefully constructed, right from algorithmic complexity for various operations, through to iterator invalidation rules. There is no benefit in implementing a container in such a way that nobody can rely on that implementation's upsides.
Could the C++ committee introduce a new container in a future standard with a different name and with different constraints, which vendors could implement as you describe? Yes, they could.
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