Open In App

Difference between Queue and Deque in C++

Queue: A Queue is a linear data structure that follows a First In First Out (FIFO) order in which the operations are performed. It is a type of container adaptor where elements are inserted into one end of the container and deleted from the other.



Functions:

Syntax:



queue <data_type> q

Below is the program to illustrate the same:




// C++ program to demonstrate the
// working of queue
#include <bits/stdc++.h>
using namespace std;
 
// Driver Code
int main()
{
    // Declare a queue
    queue<int> q;
 
    // Insert elements in the queue
    q.push(10);
    q.push(5);
    q.push(15);
    q.push(1);
 
    // Delete elements from the queue
    q.pop();
    q.pop();
 
    cout << "Elements in Queue are: ";
 
    // Print the element stored
    // in queue
    while (!q.empty()) {
        cout << q.front() << ' ';
 
        // Pop the front element
        q.pop();
    }
 
    return 0;
}

Output: 
Elements in Queue are: 15 1

 

Deque: Deque is a sequence container with the ability of expansion and contraction on both ends. It is a template of Standard Template Library or STL in C++is. It is similar to vectors but are more efficient for the insertion and deletion of elements. Contiguous storage allocation in deque may not be guaranteed as in vectors.

Functions:

Syntax:

deque<data_type> dq

Below is the program to illustrate the same:




// C++ program to demonstrate the
// working of deque
#include <bits/stdc++.h>
using namespace std;
 
// Driver Code
int main()
{
    // Declare a deque
    deque<int> dq;
 
    // Insert element in the front
    dq.push_front(10);
    dq.push_front(5);
    dq.push_front(3);
 
    // Delete elements from the front
    dq.pop_front();
    dq.pop_front();
 
    // Insert elements in the back
    dq.push_back(1);
    dq.push_back(50);
    dq.push_back(2);
 
    // Delete elements from the back
    dq.pop_back();
    dq.pop_back();
 
    cout << "Elements in deque are: ";
 
    // Print the element stored
    // in deque
    while (!dq.empty()) {
        cout << " " << dq.front();
        dq.pop_front();
    }
 
    return 0;
}

Output: 
Elements in deque are:  10 1

 

Below is the tabular difference between the queue and deque:

S.No.

Queue

Deque

1 Insertion can be done through the rear end only. Insertion is possible through both ends.
2 Deletion of elements is possible through the front end only. Deletion of elements possible through both ends.
3 Elements can not be accessed through iterators. Elements can be accessed through iterators.
4 Implemented as container adaptors. Implemented generally as some form of a dynamic array.
5 The stack can not be implemented using a queue. A stack can be implemented using deque.

Article Tags :