How to Enqueue an Element into a Queue in C++?
Last Updated :
04 Mar, 2024
Improve
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++ program to illustrate how to enqueue an element into
// a queue
#include <iostream>
#include <queue>
using namespace std;
int main()
{
// Creating a queue of integers
queue<int> myQueue;
myQueue.push(10);
myQueue.push(20);
myQueue.push(30);
// enqueue an element in a queue
int elementToEnqueue = 40;
myQueue.push(elementToEnqueue);
// Displaying the queue elements
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)