Open In App

How to Enqueue an Element into a Queue in C++?

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// 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)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads