In: Computer Science
Question 2
Indicate six key differences between a deque and a vector. When
should you choose one over the other? Explain how a deque works
internally by providing a thorough explanation of how the item
insertion happens.
Deque and Vector
The Deque is the double ended queues which contain expansion and contraction on both the ends.
It is similar to vectors but are more efficient in case insertion and deletion elements. It provides operation for insertion at front, middle and end. It performs push_front() and pop_front() operation to add and delete element from front.
Vectors are same as dynamic arrays and it has the ability the resize its size when the element is inserted or deleted. And in vectors the insertion takes place in the end. And the insertion and deletion takes place at the middle and end part only. It performs good performance while doing the insertion and deletion at the end part. But in case of insertion and deletion at the middle performs bad.
The key difference between Deque and Vector are:
Vector.
1. It provides insertion and deletion at the middle and end
2. Bad performance while doing insertion and deletion at the front.
3. Store elements contiguously.
4. Good performance for addition and deletion at the end.
5. It performs push_back() and pop_back() operation.
6. No iteration invalidation happends
Deque.
1. It provides insertion and deletion at the front, middle and end.
2. Good performance for insertion and deletion at the front.
3. While storing the elements contiguously, it contains a list of memory chunks.
4. Poor performance for insertion and deletion at the end.
5. It performs push_front() and pop_fornt() operation
6. Iteration invalidation happens.
We can choose deque over vector, if we want to add or delete the elements from the ends like we are implementing a Queue.
In the similar way, we can choose vector over deque that is we can insert or delete the elements are performed at the end like implementing the Stack.
Insertion in Deque.
For inserting an element we can use
deque insert()
By using this function we can insert the element at a specified position. That is the insertion can be done in desired position where the user want to fix the element.
And also we can insert N number of elements to this position.
It is also used the specified range of elements.
For example, if we enter the input range as
12345
Then the output must shows like:
112345
In this first we want to declare the deque after declaring it we want to print the deque. Then we want to print the declare insert() function.