queue::swap() in C++ STL

C++Server Side ProgrammingProgramming

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.

Syntax

myqueue1.swap(myqueue2);

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

Return value

This function returns nothing.

Example

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

Example

Live Demo

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

Output

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
Published on 06-Mar-2020 11:50:57