queue::swap() in C++ STL

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

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

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : AnshumanSrivastava1



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.