queue::swap() in C++ STL

In this article we will be discussing the working, syntax and examples of queue::swap() function in C++ STL.

What is a queue in C++ STL?

Queue is a simple sequence or data structure defined in the C++ STL which does insertion and deletion of the data in FIFO(First In First Out) fashion. The data in a queue is stored in continuous manner. The elements are inserted at the end and removed from the starting of the queue. In C++ STL there is already a predefined template of queue, which inserts and removes the data in the similar fashion of a queue.

What is queue::swap()?

queue::swap() is an inbuilt function in C++ STL which is declared in  header file. queue::swap() is used to swap the contents of the queue containers. This function accepts one parameter, which is the other queue container with whom we wish to swap the contents of the associated queue container.



This function accepts one parameter the second queue container with whom we wish to swap the associated queue.

Return value

This function returns nothing.


Input: queue<int> odd = {1, 3, 5};
      queue<int> eve = {2. 4. 6};
      Odd: 2 4 6
      Eve: 1 3 5


 Live Demo

#include <iostream>
#include <queue>
using namespace std;
int main(){
   queue<int> Queue_1, Queue_2;
   for(int i=0 ;i<=5 ;i++){
   for(int i=5 ;i<=10 ;i++){
   //call swap function
   cout<<"Element in Queue_1 are: ";
   while (!Queue_1.empty()){
      cout << ' ' << Queue_1.front();
   cout<<"\nElement in Queue_2 are: ";
   while (!Queue_2.empty()){
      cout << ' ' << Queue_2.front();


If we run the above code it will generate the following output −

Element in Queue_1 are: 5 6 7 8 9 10
Element in Queue_1 are: 0 1 2 3 4 5

Updated on: 06-Mar-2020


Kickstart Your Career

Get certified by completing the course

Get Started