Deque vs Vector in C++ STL
Double-ended queues are sequence containers with the feature of expansion and contraction on both the ends.
They are similar to vectors but are more efficient in case of insertion and deletion of elements. Unlike vectors, contiguous storage allocation may not be guaranteed.
Double Ended Queues are basically an implementation of the data structure double-ended queue. A queue data structure allows insertion only at the end and deletion from the front. This is like a queue in real life, wherein people are removed from the front and added at the back. Double-ended queues are a special case of queues where insertion and deletion operations are possible at both the ends.
The functions for deque are the same as a vector, with the addition of push and pop operations for both front and back.
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inserting at the end takes differential time, as sometimes there may be a need of extending the array. Removing the last element takes only constant time because no resizing happens. Inserting and erasing at the beginning or in the middle is linear in time.
Difference between Deque and Vector:
Vector Deque Provides insertion and deletion methods at middle and end Provides insertion and deletion methods at middle, end, beginning Bad performance for insertion and deletion at the front Good performance for insertion and deletion at the front Stores elements contiguously It contains lists of memory chunks where elements are stored contiguously Good performance for addition and deletion of elements at the end Poor performance for addition and deletion of elements at the end
When should we choose Deque over Vector?
We must choose Deque when our operations are adding and deleting elements in the beginning and at the end (Double-ended queue ADT).