Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


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 below example, the priority_queue::swap function is used to exchange all elements of priority_queue p_que1 with all elements of priority_queue p_que2.

#include <iostream>
#include <queue>
using namespace std;
 
int main (){
  priority_queue<int> p_que1, p_que2;

  //add new elements in the p_que1
  p_que1.push(10);
  p_que1.push(20);
  p_que1.push(30);
  p_que1.push(40);
  p_que1.push(50);

  //add new elements in the p_que2
  p_que2.push(5);
  p_que2.push(55);
  p_que2.push(555);

  swap(p_que1, p_que2);

  cout<<"After Swapping, The p_que1 contains:";
  while (!p_que1.empty()) {
    cout<<" "<<p_que1.top();
    p_que1.pop();
  }
  cout<<"\nAfter Swapping, The p_que2 contains:";
  while (!p_que2.empty()) {
    cout<<" "<<p_que2.top();
    p_que2.pop();
  }
  return 0;
}

The output of the above code will be:

After Swapping, The p_que1 contains: 555 55 5
After Swapping, The p_que2 contains: 50 40 30 20 10

❮ C++ <priority_queue> Library