In C++, std::vector::swap() exchanges the whole content of two std::vector objects. After the call, each vector 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 <vector> to use it.
This is a member of std::vector<T>, a dynamic contiguous array. Elements sit in one block, so v[i] and data() are fast. Growing past capacity() reallocates and can invalidate iterators, references, and pointers. Prefer push_back / pop_back at the end; middle inserts shift elements.
Syntax
Call swap on one vector and pass the other vector. 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 vector, use std::swap(d[0], d[1]) or std::iter_swap.
Library declarations
C++
void swap(vector& other) noexcept; // member function
template<class T, class Alloc>
void swap(vector<T, Alloc>& lhs, vector<T, Alloc>& rhs) noexcept; // free function
Parameters
Parameter
Description
other
Required. The vector to swap with. It must have the same type, such as std::vector<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 vectors with different sizes.
C++
#include <vector>
#include <iostream>
int main() {
std::vector<int> a = {1, 2, 3};
std::vector<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::vector<int>() creates a temporary, empty vector.
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 vectors of the same type. Each vector 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::vector 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 vector. The old end() iterators are invalidated.