C++ Queue STL



The C++ Queue is a container adapter that gives the programmer a FIFO (first-in, first- out) data structure.

As you see in the above animation the box which goes in first is getting processed first (ie. first-in, first-out) than others and so own.

Queue Constructor

  • back - return a reference iterator to the last element of a queue
  • empty - returns true(1) if the queue has no element else return false (0)
  • front - returns a reference iterator to the first element of a queue
  • pop - removes the first element from a queue
  • push - adds an element to the end of the queue
  • size - returns the number of the elements in the queue
Below is the implementation of the Queue Constructor.


#include<iostream>
#include<queue>
using namespace std;


int main(){
queue<int> q; // Creating a queue "q" of type integer.
// to insert data into the queue use push()
cout<<"Inserting 1,2,3,4,5 in queue\n";
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.push(5);


// Now we will check whether the queue is empty or not. 
        // (0-false/1-true)
cout<<"Is queue empty: "<<q.empty()<<"\n";
// Checking number of items in queue
cout<<"Number of items present in Queue: "<<q.size()<<"\n";


// Queue cannot be iterated like array or vectors.
int front_data = q.front();
cout<<"Data at front: "<<front_data<<"\n";
// to remove data from front positon we use pop()
q.pop();
// now front_data
front_data = q.front();
cout<<"Data at front_data: "<<front_data<<"\n";

// Printing all the remaining data in queue till queue get empty.
cout<<"\nPrinting all the remaining element\n";
while(!q.empty()){
cout<<q.front()<<"\n";
q.pop();
}
return 0;
}

Output:


Inserting 1,2,3,4,5 in queue
Is queue empty: 0
Number of items present in Queue: 5
Data at front: 1
Data at front_data: 2

Printing all the remaining element
2
3
4
5


If you have any doubts regarding this then do comment, we will be happy to help you.

Thank You for Reading.

2 Comments

  1. What is the major use of queue in cpp programming?
    some body to help.
    Sorry if am disturbing
    But I need help in that

    ReplyDelete
    Replies
    1. There are many uses of Queue, one of them is in implementation of BFS algorithm which is most used concept in Graph related Problem Solving and there are many more such use cases in Real world Problem Solving.

      Delete
Previous Post Next Post