C++ priority_queue::swap() Function
The C++ std::priority_queue::swap() function is used to swap the priority_queue efficiently, ensuring that their contents are exchanged without altering. It maitains the priority order of the elements within each queue.
The swap() function can be called in two ways: as a member function or as a non-member function. The time complexity of the swap() when used as member function is Constant i.e.O(1) orelse it is linear i.e.O(n) when used as non-member function. you can find the syntaxes of both the ways below.
Syntax
Following is the syntax for std::priority_queue::swap() function.
void swap (priority_queue& x) noexcept; or void swap (queue<T,Container,Compare>& q1,queue <T,Container,Compare>& q2) noexcept;
Parameters
- x − It indicates the another priority queue object of same type.
- q1 − It indicates the first priority_queue object.
- q2 − It indicates the second priority_queue object.
Return value
This function does not return anything.
Example
Let's look at the following example, where we are going to swap the two priority_queues.
#include <iostream>
#include <queue>
int main()
{
std::priority_queue<int> a, b;
a.push(1);
a.push(2);
b.push(11);
b.push(22);
a.swap(b);
std::cout << "After swapping:";
std::cout << "\nPriority_queue1: ";
while (!a.empty()) {
std::cout << a.top() << " ";
a.pop();
}
std::cout << "\nPriority_queue2: ";
while (!b.empty()) {
std::cout << b.top() << " ";
b.pop();
}
return 0;
}
Output
Output of the above code is as follows −
After swapping: Priority_queue1: 22 11 Priority_queue2: 2 1
Example
Consider the following example, where we are going to swap an non empty queue with empty queue and observing the output.
#include <iostream>
#include <queue>
int main()
{
std::priority_queue<int> a, b;
a.push(1);
a.push(2);
a.swap(b);
std::cout << "After swapping:\n";
std::cout << "Priority_queue1 is empty";
std::cout << "\nPriority_queue2: ";
while (!b.empty()) {
std::cout << b.top() << " ";
b.pop();
}
return 0;
}
Output
Following is the output of the above code −
After swapping: Priority_queue1 is empty Priority_queue2: 2 1
Example
In the following example, we are going to use the swap() function with move semantics to swap the priority_queue containing strings.
#include <iostream>
#include <queue>
#include <utility>
int main()
{
std::priority_queue<std::string> a, b;
a.push("Hi");
a.push("Hello");
b.push("Namaste");
b.push("Vanakam");
std::swap(a, b);
std::cout << "\n\nAfter swapping:\n";
std::cout << "Priority_queue1: ";
while (!a.empty()) {
std::cout << a.top() << " ";
a.pop();
}
std::cout << "\nPriority_queue2: ";
while (!b.empty()) {
std::cout << b.top() << " ";
b.pop();
}
return 0;
}
Output
If we run the above code it will generate the following output −
After swapping: Priority_queue1: Vanakam Namaste Priority_queue2: Hi Hello