Monday, 6 March 2017

Implementation of STL Queue in C++

To be able to use STL queue in a file of C++ source code include <queue> (C++ Standard Library header File)

Suppose that T is any type or class - say an int, float, struct, or a class, then declaration will be queue<T> q; 

You can use following inbuilt methods to perform stack operactions in STL queue:

1.   q.empty() ;     // To check if queue is empty or not
2.   q.push(x);       //To insert element x in the queue
3.   q. front();       //To access top element of the queue
3.   q. back();      //To access top element of the queue
4.   q.size();          //To know the size of queue
5.   q.pop();          //To perform pop Operation in the queue

C++ Program for demonstrating the STL queue is given below.


PROGRAM:

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

class queue_example{

   private: 
        std::queue<int> q;
   public:
        void push_element();
        void queue_empty();
        void access_front();
        void access_last();
        void pop_element();
        void queue_size();
};
void queue_example::queue_empty()
{
   if(q.empty())
   {
       cout<<"\n\nQueue is empty";
   }
   else
   {
       cout<<"\n\nQueue is not empty";
   }
}
void queue_example::push_element()
{
  cout<<"\nEnter the element: ";
  int element;
  cin>>element;
  q.push(element);
}
void queue_example::access_front()
{
  int element=q.front();
  cout<<"\n\nThe front element of queue is: "<<element;
}
void queue_example::access_last()
{
   int element=q.back();
   cout<<"\n\nLast element of the queue is: "<<element;
}
void queue_example::pop_element()
{
   q.pop();
   cout<<"\n\npop operation is performed, updating Queue";
}
void queue_example::queue_size()
{
   int size=q.size();
   cout<<"\n\nThe size of the queue is: "<<size;
}
int main()
{
    queue_example que;
    que.queue_empty();
    que.push_element();
    que.push_element();
    que.push_element();
    que.queue_size();
    que.access_front();
    que.access_last();
    que.pop_element();
    que.access_front();
    que.queue_size();
    return 0;
}


OUTPUT:


EmoticonEmoticon