×

Queue in C++

What is Queue?

As the name suggests, the queue is the type of data structure that follows the FIFO (First In - First Out) mechanism. In simple words, it is a linear data structure that resembles somewhere like a stack but has the difference of entry and exit in the elements i.e unlike stacks. It is open at both ends. One end is used to insert data (enqueue) and the other end is used to remove data (dequeue).

Queues are just like lines at a ticket counter or a cash-counter where the first entering person is the first exiting person as well.

There is a similar operation of the queue just like the stacks. Some of the operations include:

peek() ? Gets the first element of queue without

removing it.

isfull() ? Checks if it is full.

isempty() ? Checks if it is empty.

These 3 above operations are efficient enough to serve the major two operations of queues and they are:

Enqueue():  Adds or stores item in the queue.

Dequeue():  Removes or prevents access of items in the queue.

Let us now look at some pseudo-codes for understanding operations in queue.

  1. Peek()
 int peek_or_top() {
    return queue[front_element];
 } 
  • isFull()
 bool isfull()
 {
    if(rear == MaximumSize - 1)
       return true;
    else
       return false;
 } 
  • isEmpty()
 bool isempty() {
    if(front < 0 || front > rear)
       return true;
    else
       return false;
 } 

The above operational codes are just the minor steps to approach a problem involving implementations of queues. Let us look at a program to understand the flow control of queues better.

 #include<iostream>
 #include<conio.h>
 #include<stdlib.h>
 #define SIZE 5
 using namespace std;
 int q[SIZE],front=0,rear=0;
 int main()
 {
 int ch;
 void enqueue();
 void dequeue();
 void display();
 while(1)
 {
 cout<<"\n 1. add element";
 cout<<"\n 2. remove element";
 cout<<"\n 3.display";
 cout<<"\n 4.exit";
 cout<<"\n enter your choice:";
 cin>>ch;
 switch(ch)
 {
 case 1:
 enqueue();
 break;
 case 2:
 dequeue();
 break;
 case 3:
 display();
 break;
 case 4:
 exit(0);
 default:
 cout<<"\n invalid choice";
 }
 }
 }
 void enqueue()
 {
 int no;
 if (rear==SIZE && front==0)
 cout<<"queue is full";
 else
 {
 cout<<"enter the num:";
 cin>>no;
 q[rear]=no;
 }
 rear++;
 }
 void dequeue()
 {
 int no,i;
 if (front==rear)
 cout<<"queue is empty";
 else
 {
 no=q[front];
 front++;
 cout<<"\n"<<no<<" removed from the queue\n";
 }
 }
 void display()
 {
 int i,temp=front;
 if (front==rear)
 cout<<"the queue is empty";
 else
 {
 cout<<"\n element in the queue:";
 for(i=temp;i<rear;i++)
 {
 cout<<q[i]<<" ";
 }
 }
 } 

Output:

Queue in C++
Queue in C++

Explanation:

The above code depicts the flow for adding and removing elements in a queue. To understand how the enqueue and dequeue operations are performed, look at the following algorithm below.

START

1.Initialize a variable of any choice

  1. Read the variable
  2. If(top == 1) then
  3. call insert function 
  4. Else
  5. call delete function
  6. End

Algorithm for inserting in Array-Queue:

  1. If rear = NULL
  2. rear=front=0
  3. QUEUE[0]=ITEM }
  4. Else If rear= N-1 then
  5. Print "Queue Overflow!"
  6. Else
  7. QUEUE[rear+1]=ITEM
  8. rear=rear+1
  9. END.

Algorithm for deleting in Array-Queue:

1.If front==NULL then

2. Print "Queue is Empty" 

3. Else

4. ITEM=QUEUE[front]

5. If front=rear Then

6. front=rear=NULL

7. Else

8. front = front + 1

9. END

Note: The above algorithm works for mainly two operations namely enqueue and dequeue. Since these two operations are also associated with other sub-operations like peek(), isFull(), and isEmpty() we can also easily them from the above code.

Analysis of features and implementations

  1. Queues are widely used in sharing single resource serving requests like print, or task scheduling, etc.
  • Practically, queues are used in the same way the call-centers hold the calls until the representatives are free.
  • Queues can be used to handle real-time interrupts in the same order they arrive like first in first out.

Complexity Analysis

  1. Enqueue : O(1)
  2. Dequeue : O(1)
  3. Size : O(1)

Note: Queues are used where processing is not required. Processing may not need any priority since the priority queue follows a different approach. Queues follow the same approach as Breadth-First-Search (BFS).

Points to Remember:

  1. The point of entry and exit are different in a queue.
  2. Tw0 stacks can be used to make a queue.
  3. Random access is not allowed in the queue.
  4. We cannot simply add or remove elements from the middle of any queue.
  5. Inserting operation using an array is costly in the dequeue. This is because all the elements at a specific position need to be shifted by one. It is the same concept of similar people sitting on a bench and one person from one end pushes down the other to accommodate himself.

Related Topics

C++ For loop

C++ loop Statement C++ Loop statement allows us to repeat the execution of a statement or group of statements multiple times. The statement(s) repeat execution within loop until the condition of loop...

2 minutes read.

Inheritance and Friendship in C++

In this tutorial, we will look into what Inheritance and Friendship in C++ are, as well as the differences between the two. What is Inheritance in C++: In C++, inheritance is an...

2 minutes read.

Multiset in C++

Introduction Multisets are part of the C++ STL, or Standard Template Library. In C++, a multiset is a set of associative containers that hold ordered items. Items in a multiset can...

10 minutes read.

Parameterize Constructor

C++ Parameterized Constructor A constructor having parameters is known as parameterize constructor. Parameterize constructor is used to assign different values. Syntax: className(data-type argument){   // Constructor definition   }   className(data-type argument, data-type argument){   // Constructor definition   } A parameterized constructor can be passed values to constructor function in two ways: 1)...

1 minute read.

Stringstream in C++ and its applications

In this tutorial, we will explore what the stringstream in C++ is. We will also learn its application. What is stringstream? With the aid of a stringstream, user can read from a...

2 minutes read.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

C++ Void Pointer

A void pointer is a general purpose pointer that can have an address of any data type but is not related to any data type. Void Pointer Syntax: void *ptr;  We can't...

2 minutes read.

Virtual Function Vs Pure Virtual Function

Virtual activity is a member function defined in the foundation phase that can be redefined by acquired classes. Let's have a look at an example: #include <iostream>   #include <bits/stdc++.h> #include <stdlib> using namespace std;   class Base   {    ...

5 minutes read.

Add two numbers represented by two arrays in C++

The array stores a number in such a way that each digit of the number is represented by an array element. As an example, The array number 147 is 1,4,7. To add...

3 minutes read.

Hierarchical Inheritance

C++ Hierarchical Inheritance Hierarchical inheritance inherits the property of one base class in more than one derived class.   C++ Hierarchical Inheritance Example #include <iostream>   using namespace std;   class Person {       char gender[10];       int age;   public:       void getPerson()       {           cout << "Age: "; cin >> age;           cout << "Gender: "; cin >> gender;       }       void dispPerson()       {           cout << "Age: " << age << endl;           cout << "Gender: " << gender << endl;       }   };   class Employee : public Person {       float salary;   public:       void getEmployee()       {           Person::getPerson();           cout << "Salary: Rs."; cin >> salary;       }       void dispEmployee()       {           Person::dispPerson();           cout << "Salary: Rs." << salary << endl;       }   };   class Student : public Person {       char level[20];   public:       void getStudent()       {           Person::getPerson();           cout << "Class: "; cin >> level;       }       void dispStudent()       {           Person::dispPerson();           cout << "Level: " << level << endl;       }   };   int main()   {       Person per;       Employee emp;       Student stu;       cout << "Student data" << endl;       cout << "Enter data" << endl;       stu.getStudent();       cout << endl << "Displaying data" << endl;       stu.dispPerson();       cout << endl << "Staff Data" << endl;       cout << "Enter data" << endl;       emp.getEmployee();       cout << endl << "Displaying data" << endl;       emp.dispPerson();   } Output: Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age:...

1 minute read.

Type difference of Character literals in C VS C++

Character literals in C: In C, a character literal is represented by a single character enclosed in single quotes, such as 'a' or 'b'. It is of type int. This means...

5 minutes read.

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 minutes read.

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There...

3 minutes read.

C++ Virtual Function

A virtual function is such function which is declared inside the base class and redefined by the derive class. C++ uses a virtual keyword to make a function as a virtual function. The virtual...

1 minute read.

Single dimension array

C++ Array An array is a collection of data (elements) of the same data types. The elements of an array are allocated in contiguous memory allocation. Elements of the array are accessed through...

1 minute read.

Splitting a string in C++

Any programming language must have the ability to work with string data. For programming needs, we sometimes need to separate string data. Many computer languages provide a split() method that...

4 minutes read.

C++ Overriding

C++ Function Overriding When the base and derive class both contain the same function name and calling the function through derived object invokes derived class function called function overriding. Function overloading is...

1 minute read.

C++ Pointer

Pointer is a derived data type that stores the address of a variable. A pointer is used for memory management and dynamic memory allocation. Pointer works on the address of data rather than...

2 minutes read.

Print Table Using Do while Loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

4 minutes read.

Pthreads or POSIX Threads in C++

The thread API for C/C++ is implemented by pthreads or POSIX threads. It enables the multithreading system, which enables parallel and distributed processing, and the creation of new concurrent process...

3 minutes read.