priority_queue::swap() method

A priority queue is a dynamically resizing container adopter in the C++ Standard Library. Elements in a priority queue are arranged in non-decreasing order such that the first element is always the greatest element in the queue. The priority_queue::swap() is a method available in the STL which exchanges the contents of the invoking container with another container of the same type

Syntax:

priorityq_name.swap(pq2);

Parameters: The priority_queue::swap() accepts a single parameter:
•Another priority queue container of the same type

Return value: none

Example of priority_queue::swap() method

#include <iostream>>
#include <queue>

using namespace std;

void print_q(priority_queue <int> q) //helper function to print the contents of a priority queue
{
    priority_queue <int> temp = q;
    while (!temp.empty())
    {
        cout<<temp.top()<<"\t";
        temp.pop();
    }
    cout<<endl;
}


int main ()
{
    priority_queue<int> q1,q2;

    q1.push(10);
    q1.push(20);
    q1.push(40);
    q1.push(30);

    q2.push(50);
    q2.push(60);
    q2.push(70);

    cout<<"q1 before swap: \n";
    print_q(q1);

    cout<<"q2 before swap: \n";
    print_q(q2);
    cout<<endl;

    q1.swap(q2);

    cout<<"q1 after swap: \n";
    print_q(q1);

    cout<<"q2 after swap: \n";
    print_q(q2);



    return 0;
}

Output:

q1 before swap:
40  30  20  10
q2 before swap:
70  60  50

q1 after swap:
70  60  50
q2 after swap:
40  30  20  10

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top