Queues in STL are dynamic storage containers that are implemented as queue data structures in memory. They follow the FIFO (first in first out) arrangement i.e the last element that is inserted will be the last one to be popped out. Elements are stored in a contiguous manner in a queue.
Insertion is performed at the front of the queue and deletion always happens at the end of the queue. Queues are present in #include<queue> header file.
Syntax:
queue < data_type > name;
Example:
queue < int > q; //initializes a queue of size 0 which stores integer values Functions on queues
push(element): It pushes the value at the end of the queue.
Time Complexity: O(1)
Parameters: the element to be inserted
Return value: void
pop(): It deletes the first element from the queue.
Time Complexity: O(1)
Parameters: None.
Return value: void
size(): It tells us the size of the queue.
Parameters: None
Return value: integer, the size of the queue
front(): It returns the first element of the queue.
Parameters: None
Return value: the first element of the queue
back(): It returns the last element of the queue.
Parameters: None
Return value: the last element of the queue
swap(queue_name): It swaps the elements of the two queues.
Parameters: queue name to be swapped with
Return value: void
empty(): It tells us whether the queue is empty or not.
Parameters: None
Return value: boolean, true if the queue is empty else false
#include<iostream>
#include<queue>
using namespace std;
void print(queue < int > q) {
queue < int > q1 = q;
while (!q1.empty()) {
cout << q1.front() << " ";
q1.pop();
}
cout << "\n";
}
int main() {
queue < int > q;
for (int i = 0; i < 5; i++) {
q.push(i + 1);
}
cout << "Size of queue is " << q.size() << "\n";
cout << "The elements of queue are ";
print(q);
cout << "First element of the queue " << q.front() << "\n";
cout << "Last element of the queue " << q.back() << "\n";
if (!q.empty())
cout << "Queue is not empty" << "\n";
q.pop();
q.pop();
print(q);
q.push(10);
cout << "Size of queue is " << q.size() << "\n";
cout << "The elements of queue are ";
print(q);
return 0;
}Output
Size of queue is 5
The elements of queue are 1 2 3 4 5
First element of the queue 1
Last element of the queue 5
Queue is not empty
3 4 5
Size of queue is 4
The elements of queue are 3 4 5 10 Copying one queue to another
queue < int > q2 = q1; //copies queue1 into queue2 Any change in q2 will not affect q1. The time complexity of this operation is O(N) where N is the size of the q1. The same can be done using reference but it will not create a copy, it will contain a reference to the original queue.
queue < int > & q2 = q1; //q2 references q1