Last Updated : 26 Sep, 2024
Try it on GfG Practice
The std::queue::push() and std::queue::pop() functions in C++ STL are used to push the element at the back of the queue and remove the element from the front of the queue respectively. They are the member functions of the std::queue container defined inside the <queue> header file.
In this article we will learn how to use queue::push() and queue::pop() methods in C++.
queue::push()The queue::push() function in C++ STL inserts an element at the back of the queue. This operation is called push operation hence the name push() method.
Syntaxq.push(val);
Parameters
Return Value
// C++ Program to show how to use queue::push()
// to push the element at the back of queue
#include <bits/stdc++.h>
using namespace std;
int main() {
queue<int> q;
// Inserting elements at the back of queue
q.push(0);
q.push(1);
q.push(2);
// Printing queue
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
return 0;
}
Time Complexity: O(1)
Auxiliary Space: O(1)
The queue::pop() function in C++ STL removes an element from the front of the queue. This operation is called pop operation hence the name. It works according to the FIFO (First-In-First-Out) order of deletion i.e. the element that was inserted first will be removed first.
Syntaxq.pop();
Parameters
Return Value
// C++ Program to show how to use queue::pop()
// to remove the element from the front of queue
#include <bits/stdc++.h>
using namespace std;
int main() {
queue<int> q;
// Inserting few elements at the back of queue
q.push(0);
q.push(1);
q.push(2);
// Remove element from the front of queue
q.pop();
// Printing queue
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
return 0;
}
Time Complexity: O(1)
Auxiliary Space: O(1)
The following table list the main differences between queue::push() and queue::pop():
queue push()
queue pop()
It is used to push a new element at the end of the queue. It is used to remove the front element from the queue. Its syntax is -:RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4