Open In App

queue::swap() in C++ STL

Improve
Improve
Like Article
Like
Save
Share
Report

Queue is also an abstract data type or a linear data structure, which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). In a FIFO data structure, the first element added to the queue will be the first one to be removed. queue::swap() swap() function is used to exchange the contents of two queues but the queues must be of same type, although sizes may differ. 

Syntax:

queue1.swap(queue2)
            OR
swap(queue1, queue2)

Parameters:
queue1 is the first queue object.
queue2 is the second queue object.

Return value: None 

Examples:

Input :  queue1 = {1, 2, 3, 4}
         queue2 = {5, 6, 7, 8}
         queue1.swap(queue2);
Output : queue1 = {5, 6, 7, 8}
         queue2 = {1, 2, 3, 4}

Input  : queue1 = {'a', 'b', 'c', 'd', 'e'}
         queue2 = {'f', 'g', 'h', 'i'}
         queue1.swap(queue2);
Output : queue1 = {'f', 'g', 'h', 'i'}
         queue2 = {'a', 'b', 'c', 'd', 'e'}

Errors and Exceptions 1. It throws an error if the queues are not of the same type. 2. It has a basic no exception throw guarantee otherwise. 

CPP




// CPP program to illustrate
// Implementation of swap() function
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    // Take any two queues
    queue<char> queue1, queue2;
    int v = 96;
    for (int i = 0; i < 5; i++) {
      queue1.push(v + 1);
      v++;
    }
 
   for (int i = 0; i < 4; i++) {
      queue2.push(v + 1);
      v++;
    }
       
    // Swap elements of queues
    queue1.swap(queue2);
 
    // Print the first queue
    cout << "queue1 = ";
    while (!queue1.empty()) {
      cout << queue1.front() << " ";
      queue1.pop();
   }
 
    // Print the second set
    cout << endl << "queue2 = ";
    while (!queue2.empty()) {
      cout << queue2.front() << " ";
      queue2.pop();
   }
         
    return 0;
}


Output:

queue1 = f g h i 
queue2 = a b c d e 

Time complexity: Linear i.e. O(n)

Auxiliary Space : O(n) because using queue



Last Updated : 08 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads