The push() and pop() functions are member functions of the std::queue container adapter in C++. They are used to insert and remove elements while maintaining the First In First Out (FIFO) order of a queue.
- push() inserts a new element at the back of the queue.
- pop() removes the element from the front of the queue.
queue::push()
The queue::push() function inserts a new element at the end of the queue while maintaining the First-In, First-Out (FIFO) order.
- Inserts the new element at the back of the queue.
- Increases the size of the queue by one.
- Does not return any value.
Syntax
q.push(val);
Parameters: value - The element to be inserted into the queue.
#include <iostream>
#include <queue>
using namespace std;
int main() {
queue<int> q;
q.push(10);
q.push(20);
q.push(30);
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
return 0;
}
Output
10 20 30
Explanation: The elements are inserted at the back of the queue in the order 10, 20, and 30. Since a queue follows FIFO order, they are removed in the same order.
queue::pop() in C++
The queue::pop() function removes the element present at the front of the queue according to the FIFO principle.
- Removes the front (oldest) element from the queue.
- Decreases the size of the queue by one.
- Does not return the removed element and causes undefined behavior if the queue is empty.
Syntax
q.pop();
Parameters: This function does not take any parameters.
#include <iostream>
#include <queue>
using namespace std;
int main() {
queue<int> q;
q.push(10);
q.push(20);
q.push(30);
q.pop();
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
return 0;
}
Output
20 30
Explanation: The first inserted element (10) is removed using pop(), and the remaining elements are printed.
Difference Between queue::push() and queue::pop()
The following table list the main differences between queue::push() and queue::pop():
| Feature | queue::push() | queue::pop() |
|---|---|---|
| Purpose | Inserts an element into the queue | Removes an element from the queue |
| Position | Inserts at the back | Removes from the front |
| Syntax | q.push(value) | q.pop() |
| Parameters | Takes one parameter | Takes no parameters |
| Return Value | Does not return any value | Does not return any value |
| Time Complexity | O(1) | O(1) |