Thursday, June 28, 2012

Queue STL in c++


Queue is a data structure that follows the FIFO (first in first out ). We can accass it by using STL easily.
First of all we have use a header        #include <queue>


Queues allow data to be added at one end and taken out of the other end. To be able to use STL queues add this before you start using them in your source code:     
Suppose that T is any type or class - say an int, a float, a struct, or a class, then
  queue<T> q;
declares a new and empty queue called q. Given an object q:

test to see if q is empty:
           q.empty()

find how many items are in q:
           q.size()

push a t:T onto the end of q:
           q.push(t)

pop the front of q off q:
           q.pop()

get the front item of q:
           q.front()
    • change the front item:
           q.front() = expression.
get the back item of q:
           q.back()
    • change the back item:
           q.back() = expression.




For Example
#include<queue>
//in any data type you can take into queue , int ,float,char,double even custom data types like struct .
Queue<T> q;   // here T is any data type that you can use in your program.
//if T is int follow the example is given bellow.
q.push(10);
q.push(20);
q.push(30);
q.push(40);
q.push(50);
q.push(60);
//here 10,20,30,40,50,60  are the six element are pushed. You can access it by
q.front()=10;
q.back()=60;
//you can pop the front element;
q.pop();
//front element will be 20;
q.front()=20;
you can change the front and back element by
q.front()=any value ;
q.back()=any value ;



No comments:

Post a Comment