queue::swap() method

Queues are an abstract data type, specifically designed to operate in a FIFO context (first-in-first-out). The elements are inserted into one end of the container and extracted from the other. They are a type of container adaptor in the C++ Standard Library. The queue::swap() is a method available in the STL which exchanges the contents of two queues (of the same type)

Syntax:

q1_name.swap(q2_name);

Parameters: The queue::swap() method accepts a single parameter:
•Another queue of the same type (sizes may differ)
Return value: none

Example of queue::swap() method

#include <iostream>
#include <queue>

using namespace std;

void printq(queue<int> q)
{
  while(!q.empty())
  {
    cout<<q.front()<<"  ";
    q.pop();
  }

  cout<<endl;
}

int main() 
{
  queue<int> q1;
  q1.push(5);
  q1.push(6);
  q1.push(7);
  q1.push(8);

  queue<int> q2;
  q2.push(1);
  q2.push(2);
  q2.push(3);

  cout<<"Q1 before swap: \n";
  printq(q1);

  cout<<"Q2 before swap: \n";
  printq(q2);

  q1.swap(q2);

  cout<<"Q1 after swap: \n";
  printq(q1);

  cout<<"Q2 after swap: \n";
  printq(q2);
}

Output:

Q1 before swap: 
5  6  7  8  
Q2 before swap: 
1  2  3  
Q1 after swap: 
1  2  3  
Q2 after swap: 
5  6  7  8  

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top