In C++11, swap()exchanges everything inside two std::priority_queue objects. After a.swap(b), queue a holds what b had, and queue b holds what a had.
The swap is fast, because the queues just trade their inner containers. No element is copied one by one. Both queues must have the same type, which includes the element type, the container, and the comparison. You can also write std::swap(a, b).
This function is a member function of std::priority_queue<T>, declared in the <queue> header. It needs C++11 or newer (-std=c++11). You call it with a dot, for example pq.swap(...).
Syntax
Call swap() on one queue and pass the other queue. Or call the non-member std::swap with both.
C++
std::priority_queue<int> a;
std::priority_queue<int> b;
a.push(3);
b.push(20);
a.swap(b); // a now has 20, b now has 3
std::swap(a, b); // swaps them back
Call
What it does
a.swap(b)
Exchanges the contents of a and b. Nothing is returned.
std::swap(a, b)
The non-member version. It does the same thing and calls a.swap(b) inside.
Swapping does not change the order of elements inside each queue, and it does not call top() or pop(). priority_queue has no clear(), so swapping with an empty queue is a common way to empty it.
Library declarations
C++
void swap(priority_queue& other) noexcept(/* see below */); // C++11
// Non-member overload (C++11):
template<class T, class Container, class Compare>
void swap(priority_queue<T, Container, Compare>& lhs,
priority_queue<T, Container, Compare>& rhs);
// priority_queue<T, Container, Compare> from <queue>
// It swaps the container c and the comparison object comp.
Parameters
Parameter
Description
other
Required. Another priority queue of the same type. It trades its contents with the queue you call swap() on.
Return Value
Return Value
Description
Nothing
swap() returns void. Both queues are changed in place.
C++ Examples
Example 1 — Swap Two Queues
Fill two queues with different numbers. After swap(), the tops and sizes are exchanged.