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
template <class T, class Container> void swap (queue<T,Container>& lhs, queue<T,Container>& rhs) noexcept(noexcept(lhs.swap(rhs)));
Parameters
lhs |
First queue. |
rhs |
Second queue. |
Return Value
None.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the 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); swap(que1, 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