Should I use deque instead of vector if i'd like to push elements also in the beginning of the container? When should I use list and what's the point of it?
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.
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".
Vector may have a default size. List does not have default size. In vector, each element only requires the space for itself only. In list, each element requires extra space for the node which holds the element, including pointers to the next and previous elements in the list.
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.
Use deque
if you need efficient insertion/removal at the beginning and end of the sequence and random access; use list
if you need efficient insertion anywhere, at the sacrifice of random access. Iterators and references to list
elements are very stable under almost any mutation of the container, while deque
has very peculiar iterator and reference invalidation rules (so check them out carefully).
Also, list
is a node-based container, while a deque
uses chunks of contiguous memory, so memory locality may have performance effects that cannot be captured by asymptotic complexity estimates.
deque
can serve as a replacement for vector
almost everywhere and should probably have been considered the "default" container in C++ (on account of its more flexible memory requirements); the only reason to prefer vector
is when you must have a guaranteed contiguous memory layout of your sequence.
deque
and vector
provide random access, list
provides only linear accesses. So if you need to be able to do container[i], that rules out list
. On the other hand, you can insert and remove items anywhere in a list
efficiently, and operations in the middle of vector
and deque
are slow.
deque
and vector
are very similar, and are basically interchangeable for most purposes. There are only two differences worth mentioning. First, vector
can only efficiently add new items at the end, while deque
can add items at either end efficiently. So why would you ever use a vector
then? Unlike deque
, vector
guarantee that all items will be stored in contiguous memory locations, which makes iterating through them faster in some situations.
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