The swap() function in C++ STL exchanges the contents of two queues efficiently. It is a member function of the std::queue container adapter and is defined in the <queue> header file.
- Exchanges the contents of two queues without copying individual elements.
- Both queues must have the same element type and underlying container type.
#include <iostream>
#include <queue>
using namespace std;
int main()
{
queue<int> q1, q2;
q1.push(1);
q1.push(2);
q1.push(3);
q2.push(10);
q2.push(20);
q2.push(30);
q2.push(40);
q1.swap(q2);
cout << "q1: ";
while (!q1.empty())
{
cout << q1.front() << " ";
q1.pop();
}
cout << "\nq2: ";
while (!q2.empty())
{
cout << q2.front() << " ";
q2.pop();
}
return 0;
}
Output
q1: 10 20 30 40 q2: 1 2 3
Explanation: After calling q1.swap(q2), the contents of the two queues are exchanged. The elements of q1 become the elements of q2 and vice versa.
Syntax
queue1.swap(queue2);
or
swap(queue1, queue2);
- Parameters: queue1 is the first queue and queue2 is the second queue.
- Return Value: The function does not return any value.
Using the Non-Member swap() Function
The STL also provides a non-member swap() function that performs the same operation.
#include <iostream>
#include <queue>
using namespace std;
int main()
{
queue<char> q1, q2;
q1.push('A');
q1.push('B');
q1.push('C');
q2.push('X');
q2.push('Y');
swap(q1, q2);
cout << "Front of q1: " << q1.front() << endl;
cout << "Front of q2: " << q2.front() << endl;
return 0;
}
Output
Front of q1: X Front of q2: A
Characteristics of queue::swap()
The swap() function provides an efficient way to exchange the contents of two queues.
- Both queues must have the same type.
- The sizes of the queues may differ.
- No elements are copied individually.
- The operation preserves the order of elements inside each queue.
- Both member swap() and non-member swap() perform the same task.
Errors and Exceptions
The queue::swap() function is safe and efficient, but there are a few conditions that should be kept in mind.
- A compilation error occurs if the two queues have different types.
- The function provides a no-throw guarantee when the underlying container supports a no-throw swap.
- The sizes of the two queues do not need to be the same for swapping.