priority_queue::swap() in C++ STL
Last Updated :
17 Jan, 2023
Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. However, in C++ STL (by default) the largest element is at the top. We can also create a priority queue having the smallest element at the top by simply passing an extra parameter while creating the priority queue.
priority_queue::swap()
This function is used to swap the contents of one priority queue with another priority queue of same type and same or different size.
Time complexity: O(1)
Syntax :
priorityqueuename1.swap(priorityqueuename2)
Parameters :
The name of the priority queue with which the contents have to be swapped.
Result :
All the elements of the 2 priority queues are swapped.
Examples:
Input : mypqueue1 = {1, 2, 3, 4}
mypqueue2 = {3, 5, 7, 9}
mypqueue1.swap(mypqueue2);
Output : mypqueue1 = {9, 7, 5, 3}
mypqueue2 = {4, 3, 2, 1}
Input : mypqueue1 = {1, 3, 5, 7}
mypqueue2 = {2, 4, 6, 8}
mypqueue1.swap(mypqueue2);
Output : mypqueue1 = {8, 6, 4, 2}
mypqueue2 = {7, 5, 3, 1}
Note: In priority_queue container, the elements are printed in reverse order because the top is printed first
then moving on to other elements.
Errors and Exceptions 1. It throws an error if the priority queues are not of the same type. 2. It has a basic no exception throw guarantee otherwise.
Example 1: It swaps two priority queue of same type and same size
CPP
#include <iostream>
#include <queue>
using namespace std;
int main()
{
priority_queue< int > mypqueue1;
priority_queue< int > mypqueue2;
mypqueue1.push(1);
mypqueue1.push(2);
mypqueue1.push(3);
mypqueue1.push(4);
mypqueue2.push(3);
mypqueue2.push(5);
mypqueue2.push(7);
mypqueue2.push(9);
mypqueue1.swap(mypqueue2);
cout << "mypqueue1 = " ;
while (!mypqueue1.empty()) {
cout << mypqueue1.top() << " " ;
mypqueue1.pop();
}
cout << endl
<< "mypqueue2 = " ;
while (!mypqueue2.empty()) {
cout << mypqueue2.top() << " " ;
mypqueue2.pop();
}
return 0;
}
|
Output
mypqueue1 = 9 7 5 3
mypqueue2 = 4 3 2 1
Example 2: It swaps two priority queue of same type but different size
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
priority_queue< int > mypqueue1;
priority_queue< int > mypqueue2;
mypqueue1.push(1);
mypqueue1.push(2);
mypqueue1.push(3);
mypqueue1.push(4);
mypqueue1.push(5);
mypqueue2.push(3);
mypqueue2.push(5);
mypqueue2.push(7);
mypqueue2.push(9);
mypqueue1.swap(mypqueue2);
cout<< "mypqueue1 = " ;
while (!mypqueue1.empty()) {
cout<<mypqueue1.top() << " " ;
mypqueue1.pop();
}
cout<<endl<< "mypqueue2 = " ;
while (!mypqueue2.empty()) {
cout<<mypqueue2.top() << " " ;
mypqueue2.pop();
}
return 0;
}
|
Output
mypqueue1 = 9 7 5 3
mypqueue2 = 5 4 3 2 1
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...