C++ queue - swap() Function
The C++ queue::swap function is used to exchange all elements of one queue with all elements of another queue. To apply this function, the data-type of both queues must be same, although the size may differ.
Syntax
void swap (queue& other) noexcept(/* see below */);
Exchanges the content of the container adaptor(*this) with those of others.
Parameters
other |
Specify queue, whose elements need to be exchanged with another queue. |
Return Value
None.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the queue::swap function is used to exchange all elements of queue que1 with all elements of queue que2.
#include <iostream> #include <queue> using namespace std; int main (){ queue<int> que1, que2; //add new elements in the que1 que1.push(10); que1.push(20); que1.push(30); que1.push(40); que1.push(50); //add new elements in the que2 que2.push(5); que2.push(55); que2.push(555); que1.swap(que2); cout<<"After Swapping, The que1 contains:"; while (!que1.empty()) { cout<<" "<<que1.front(); que1.pop(); } cout<<"\nAfter Swapping, The que2 contains:"; while (!que2.empty()) { cout<<" "<<que2.front(); que2.pop(); } return 0; }
The output of the above code will be:
After Swapping, The que1 contains: 5 55 555 After Swapping, The que2 contains: 10 20 30 40 50
❮ C++ <queue> Library