As vector
and deque
both provides a function to push_back
the element at the last.
where deque
also provides a function push_front
to insert the element at the beginning, which is bit costly in case of vector
.
My question is when we can achieve the same functionality (push_back
) of vector
by using deque
, then why vector
is required?
Deque is a type of data structure that allows for the insertion and deletion of elements at the middle, end, and beginning. Vector is a type of data structure that allows for insertion and deletion of elements within the Data structure using the method at the middle of the end.
The deque is a bit slower than the vector, that is logical because here there are more cache misses due to the segmented parts. The performance of the list are still poor but the gap is decreasing. The interesting point is that deque is now faster than vector.
One should choose deque over vector if he wants to either add or delete from both the ends like implementing a Queue. When to choose vector over deque: One should choose vector if insertion or deletions are required mostly in end like implementing a Stack.
A deque is a set of linked memory blocks, where more than one element is stored in each memory block. A list is a set of elements dispersed in memory, i.e.: only one element is stored per memory "block".
One main difference between vectors and deques is that the latter allows efficient insertion at the front of the structure as well as the back.
Deques also do not guarantee that their elements are contiguous in memory so the at-style operator (indexing) may not be as efficient.
Note that the difference is unlikely to matter in practice for smaller collections but would generally become more important if, for example, the collection size increases or you're modifying it many times per second.
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