Signup/Sign In

DEQUE Container in C++ STL

Deque is a shorthand for doubly ended queue. Deque allows fast insertion and deletion at both ends of the queue. Although we can also use vector container for the insertion and deletion at both of its ends, but insertion and deletion at the front of the array is costlier than at the back, in case of deque but deque are more complex internally.

Syntax for creating a Deque is:

deque< object_type > deque_name;

Member Functions of Deque

Following are some of the commonly used functions of Deque Container in STL:


push_back, push_front and insert functions

push_back(element e) inserts an element e at the back of the deque, push_front(element e) inserts the element e at the front of the deque.

insert() method has three variations :

  • insert(iterator i, element e) : Inserts element e at the position pointed by iterator i in the deque.
  • insert(iterator i, int count, element e) : Inserts element e, count number of times from the position pointed by iterator i.
  • insert(iterator i, iterator first, iterator last) : Inserts the element in the range [first,last] at the position pointed by iterator i in deque.
#include <iostream>
#include <deque>
#include <vector>

using namespace std;

int main ()
{

    int a[] = { 1,5,8,9,3 };
    deque<int> dq(a, a+5);
    /* creates s deque with elements 1,5,8,9,3  */
    
    
    dq.push_back(10);
    /* now dq is : 1,5,8,9,3,10 */
    
    dq.push_front(20);
    /* now dq is : 20,1,5,8,9,3,10  */
    
    deque<int>::iterator i;
    
    i=dq.begin()+2;
    /* i points to 3rd element in dq */
    
    dq.insert(i,15);
    /* now dq 20,1,15,5,8,9,3,10  */
    
    int a[]={7,7,7,7};
    
    d1.insert(dq.begin() , a , a+4 );
    /* now dq is 7,7,7,7,20,1,15,5,8,9,3,10  */
}

pop_back and pop_front functions

pop_back() removes an element from the back of the deque whereas pop_front removes an element from the front of the deque, both decreasing the size of the deque by one.

#include <iostream>
#include <deque>
#include <vector>

using namespace std;

int main ()
{

    int a[] = { 1,5,8,9,3,5,6,4 };
    deque<int> dq(a,a+8);
    /* creates s deque with elements 1,5,8,9,3,5,6,4  */
    
    
    dq.pop_back();
    /* removes an element from the back */
    /* now the deque dq is : 1,5,8,9,3,5,6 */
    
    dq.pop_front();
    /* now dq is : 1,5,8,9,3,5,6  */
}

empty, size and max_size functions

empty() returns Boolean true if the deque is empty, else Boolean false is returned. size() returns the number of elements present in the deque and max_size() returns the number of element the given deque can hold.


swap function

This method can be used to swap elements of two deques.