In C++, std::deque::swap() exchanges the whole content of two std::deque objects. After the call, each deque holds what the other one held before.
It is fast because it does not copy or move the elements one by one. It only swaps the internal data. Include <deque> to use it.
This is a member of std::deque<T>, a double-ended queue. A deque is fast at adding and removing at both ends, and it allows access by index like std::vector. Unlike a vector, its elements are stored in several blocks, not in one contiguous block.
Syntax
Call swap on one deque and pass the other deque. Both must hold the same element type.
C++
a.swap(b);
std::swap(a, b);
Call
What it does
a.swap(b)
The member function. a gets the elements of b, and b gets the elements of a.
std::swap(a, b)
The free function. It gives the same result and calls the member function for you.
To swap just two elements inside one deque, use std::swap(d[0], d[1]) or std::iter_swap.
Library declarations
C++
void swap(deque& other) noexcept; // member function
template<class T, class Alloc>
void swap(deque<T, Alloc>& lhs, deque<T, Alloc>& rhs) noexcept; // free function
Parameters
Parameter
Description
other
Required. The deque to swap with. It must have the same type, such as std::deque<int>.
Return Value
Return Value
Description
Nothing
swap() returns void. Both deques are changed.
C++ Examples
Example 1 — Swap Two Deques with swap()
Exchange the content of two deques with different sizes.
C++
#include <deque>
#include <iostream>
int main() {
std::deque<int> a = {1, 2, 3};
std::deque<int> b = {7, 8};
a.swap(b);
std::cout << "a: ";
for (int n : a) std::cout << n << ' ';
std::cout << '\n';
std::cout << "b: ";
for (int n : b) std::cout << n << ' ';
std::cout << '\n';
return 0;
}
Output
a: 7 8
b: 1 2 3
How It Works
a starts with three elements, and b starts with two.
a.swap(b) exchanges everything. The sizes are swapped too.
Now a prints 7 8 and b prints 1 2 3. No element was copied one by one.
Example 2 — std::swap() on Deques
The free function works in the same way and reads naturally.
std::deque<int>() creates a temporary, empty deque.
swap(d) gives the five elements to the temporary and gives its empty content to d.
The temporary is destroyed at the end of the line, together with the old memory. Before shrink_to_fit() existed, this was the usual trick to free memory.
Frequently Asked Questions
It exchanges the whole content of two deques of the same type. Each deque ends up with the elements of the other.
Yes. It takes constant time, because only internal data is exchanged and no element is copied.
For std::deque they give the same result. The non-member std::swap calls the member swap for you.
Yes. After the swap, the sizes are exchanged too.
Iterators and references stay valid, but they now refer to elements that live in the other deque. The old end() iterators are invalidated.