C++ Standard Library C++ STL Library

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

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 example below, the priority_queue::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);

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