Queues are a type of container adaptors which operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front.
Syntax:
queue< object_type > queue_name;
Queue functions are:
- empty() – Returns whether the queue is empty.
- size() – Returns the size of the queue.
- queue::swap() in C++ STL – Exchange the contents of two queues but the queues must be of same type, although sizes may differ.
- queue::emplace() in C++ STL – Insert a new element into the queue container, the new element is added to the end of the queue.
- queue::front() and queue::back() in C++ STL – front() function returns a reference to the first element of the queue. back() function returns a reference to the last element of the queue.
- push(g) and pop() – push() function adds the element ‘g’ at the end of the queue. pop() function deletes the first element of the queue.
// Queue in Standard Template Library (STL)
#include <iostream>
#include <queue>
using namespace std;
void showQueue(queue<int> tcp_queue)
{
queue<int> tsp = tcp_queue;
while (!tsp.empty()) {
cout << '\t' << tsp.front();
tsp.pop();
}
cout << '\n';
}
int main()
{
queue<int> tsp_queue;
tsp_queue.push(10);
tsp_queue.push(20);
tsp_queue.push(30);
cout << "The queue tsp_queue is : ";
showQueue(tsp_queue);
cout << "\ntsp_queue.size() : " << tsp_queue.size();
cout << "\ntsp_queue.front() : " << tsp_queue.front();
cout << "\ntsp_queue.back() : " << tsp_queue.back();
cout << "\ntsp_queue.pop() : ";
tsp_queue.pop();
showq(tsp_queue);
return 0;
}
/*
Output :
The queue gquiz is : 10 20 30
gquiz.size() : 3
gquiz.front() : 10
gquiz.back() : 30
gquiz.pop() : 20 30
*/