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

void swap (priority_queue& other) noexcept (/*see below*/);

Exchanges the content of the container adaptor(*this) with those of others.


Parameters

other Specify priority_queue, whose elements need to be exchanged with another 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);

  p_que1.swap(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