C++ Insert Element to a Queue

ht‮/:spt‬/www.theitroad.com

In C++, you can add elements to the back of a queue using the push() method. Here's an example:

#include <iostream>
#include <queue>

using namespace std;

int main() {
    queue<int> myQueue;
    
    myQueue.push(10);  // Add 10 to the back of the queue
    myQueue.push(20);  // Add 20 to the back of the queue
    myQueue.push(30);  // Add 30 to the back of the queue
    
    cout << "Size of queue: " << myQueue.size() << endl;
    
    return 0;
}

In the example above, we first create an empty queue called myQueue. We then use the push() method to add three integers (10, 20, and 30) to the back of the queue. Finally, we use the size() method to print the number of elements in the queue. The output of this program would be:

Size of queue: 3

Note that the push() method is used to add elements to the back of the queue. If you want to insert elements in the middle of the queue, you may want to consider using a different container, such as a deque.