I know that deque is more efficient than vector when insertions are at front or end and vector is better if we have to do pointer arithmetic. But which one to use when we have to perform insertions in middle.? and Why.?
[2] Inserting an element at the beginning or end of a deque takes amortized constant time. Inserting an element in the middle is linear in n, where n is the smaller of the number of elements from the insertion point to the beginning, and the number of elements from the insertion point to the end.
Advantages of Deque:You are able to add and remove items from the both front and back of the queue. Deques are faster in adding and removing the elements to the end or beginning. The clockwise and anti-clockwise rotation operations are faster in a deque.
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.
Also, deque supports range-based for loop iteration, which is unavailable for stack and queue(both of them require to create temporary copy for iteration). Thereby deque supports all operations much more faster than both stack and queue.
You might think that a deque
would have the advantage, because it stores the data broken up into blocks. However to implement operator[]
in constant time requires all those blocks to be the same size. Inserting or deleting an element in the middle still requires shifting all the values on one side or the other, same as a vector
. Since the vector
is simpler and has better locality for caching, it should come out ahead.
Selection criteria with Standard library containers is, You select a container depending upon:
If you want to perform large number of insertions in the middle you are much better off using a std::list
.
If the choice is just between a std::deque
and std::vector
then there are a number of factors to consider:
max_size()
might be larger for deques.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