How to Enqueue an Element into a Queue in C++?
Last Updated :
04 Mar, 2024
In C++ STL, we have a queue container that simulates the queue data structure and follows the FIFO (First In, First Out) rule. In this article, we will learn how to enqueue (insert) an element into a queue in C++.
Example:
Input:
myQueue = {10, 20, 30};
elementToEnqueue= 40
Output:
Queue after enqueue: 10 20 30 40
Add an Element to a Queue in C++
To enqueue an element into a std::queue in C++ STL, we can use the std::queue::push() function that inserts a new element at the end of the queue, after its current last element.
C++ Program to Enqueue an Element into a Queue
The below example demonstrates how we can enqueue an element into a queue in C++.
C++
#include <iostream>
#include <queue>
using namespace std;
int main()
{
queue< int > myQueue;
myQueue.push(10);
myQueue.push(20);
myQueue.push(30);
int elementToEnqueue = 40;
myQueue.push(elementToEnqueue);
cout << "Elements in a Queue are:" << endl;
while (!myQueue.empty()) {
cout << myQueue.front() << " " ;
myQueue.pop();
}
cout << endl;
return 0;
}
|
Output
Elements in a Queue are:
10 20 30 40
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...