In C++11, swap()exchanges everything between two std::queue objects. After the call, each queue holds what the other one held before, in the same order.
The swap is fast because the queues only exchange their internal containers, so no elements are copied one by one. A queue has no clear(), so swapping with an empty queue is also a common way to empty one.
This function is a member function of std::queue<T>, declared in the <queue> header. It needs C++11 or newer (-std=c++11). You call it with a dot, for example q.swap(...).
Syntax
Call swap() on one queue and pass the other queue. Both queues must have exactly the same type.
C++
std::queue<int> a;
std::queue<int> b;
a.push(1);
b.push(9);
a.swap(b); // member form
std::swap(a, b); // non-member form, swaps back
Call
What it does
a.swap(b)
Exchanges the contents of a and b. Both must be the same queue<T, Container> type.
std::swap(a, b)
The non-member form. It calls a.swap(b) and works in generic code.
swap() takes constant time and does not move individual elements. Both queues must use the same element type and the same underlying container, so a queue<int> cannot swap with a queue<long>. It needs C++11 or newer.
Library declarations
C++
void swap(queue& other) noexcept(/* see below */); // C++11
template<class T, class Container>
void swap(queue<T, Container>& a,
queue<T, Container>& b) noexcept(/* see below */); // C++11
// queue<T, Container> from <queue>
// It swaps the underlying containers: swap(c, other.c).
Parameters
Parameter
Description
other
Required. The queue to exchange with. It must have the same element type and the same underlying container type. It is changed too.
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 sizes, swap them, and see that sizes and fronts move together.
std::queue<int>() creates a brand new empty queue. Its swap(q) trades places with q, so q becomes empty at once.
The temporary queue now holds the four old numbers and is destroyed at the end of the line. After that, size() is 0 and empty() is true.
Frequently Asked Questions
It exchanges the contents of two queues. After the call, each queue holds what the other one held, in the same order. It was added in C++11.
No. Both queues must have the same element type and the same underlying container. A queue<int> cannot swap with a queue<double>.
No. It swaps the internal containers, which is a constant-time operation, so it is fast even for large queues.
A queue has no clear() function. Use std::queue<int>().swap(q); or assign q = std::queue<int>(); or pop() in a loop until empty() is true.
They do the same thing. The member form is called on one queue. The non-member form takes both queues and calls the member form, which is useful in generic code.