C++ priority_queue - swap() Function
The C++ priority_queue swap() function is used to exchange all elements of one priority_queue with all elements of another priority_queue. To apply this function, the data-type of both priority_queues must be same, although the size may differ.
Syntax
template <class T, class Container, class Compare> void swap (priority_queue<T,Container,Compare>& lhs, priority_queue<T,Container,Compare>& rhs) noexcept(noexcept(lhs.swap(rhs)));
Parameters
lhs |
First priority_queue. |
rhs |
Second priority_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 priority_queue pque1 with all elements of priority_queue pque2.
#include <iostream> #include <queue> using namespace std; int main (){ priority_queue<int> pque1, pque2; //add new elements in the pque1 pque1.push(10); pque1.push(20); pque1.push(30); pque1.push(40); pque1.push(50); //add new elements in the pque2 pque2.push(5); pque2.push(55); pque2.push(555); swap(pque1, pque2); cout<<"After Swapping, The pque1 contains:"; while (!pque1.empty()) { cout<<" "<<pque1.top(); pque1.pop(); } cout<<"\nAfter Swapping, The pque2 contains:"; while (!pque2.empty()) { cout<<" "<<pque2.top(); pque2.pop(); } return 0; }
The output of the above code will be:
After Swapping, The pque1 contains: 555 55 5 After Swapping, The pque2 contains: 50 40 30 20 10
❮ C++ <queue> Library