Queue is a type of container adapter specially designed to work in first in first out context. In queue the element is inserted at the back-end and removed from front-end. For working on FIFO context queues are mainly used.
Basic Functions
Following are basic functions used with Queue:
Function | Description |
---|---|
empty() | Returns true if queue is empty |
size() | Returns the size of queue |
push(g) | Inserts element at the end of queue |
pop() | Removes element from the front of queue |
queue::swap() in C++ STL | |
queue::swap() in C++ STL | It will exchange contents of queue only if queue type is same. If there is difference in size then its ok |
queue::front() in C++ STL | Returns reference of first element in queue |
queue::back() in C++ STL | Returns reference of last element in queue |
Example
Following is an example for C++ queue:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | // CPP code for illustration of Queue in Standard Template Library (STL) #include <iostream> #include <queue> using namespace std; void showQueue(queue <int> tq) { queue <int> t = tq; cout << '\n'; while (!t.empty()){ cout << t.front() << ' '; t.pop(); } cout << '\n'; } int main(){ queue <int> qfirst; qfirst.push(5); qfirst.push(10); qfirst.push(15); qfirst.push(20); qfirst.push(25); cout << "Display queue qfirst : "; showQueue(qfirst); cout << "\nQueue Size qfirst.size() : " << qfirst.size(); cout << "\nElement at front qfirst.front() : " << qfirst.front(); cout << "\nElement at back qfirst.back() : " << qfirst.back(); cout << "\n\nDisplaying queue before pop() operation : "; showQueue(qfirst); cout << "\nqfirst.pop() \n"; qfirst.pop(); cout << "\nDisplaying queue after pop() operation : "; showQueue(qfirst); return 0; } |
The output should be:
Display queue qfirst :
5 10 15 20 25
5 10 15 20 25
Queue Size qfirst.size() : 5
Element at front qfirst.front() : 5
Element at back qfirst.back() : 25Displaying queue before pop() operation :
5 10 15 20 25
qfirst.pop()
Displaying queue after pop() operation :
10 15 20 25