In C++, std::array::swap() exchanges the contents of two arrays. After the call, the first array holds the values of the second one, and the other way round.
Both arrays must have the same element type and the same size. The swap goes element by element, so it takes time proportional to N. Include <array> to use it.
This is a member of std::array<T, N>, not of a plain C array and not of std::vector. A std::array has a fixed size N that is part of its type, and it lives on the stack like a normal variable.
Syntax
Call swap on one array and pass the other array.
C++
a.swap(b);
std::swap(a, b);
Call
What it does
a.swap(b)
Exchanges all elements of a and b.
std::swap(a, b)
The non-member version. It gives the same result for arrays.
Both arrays must be the same type, for example std::array<int, 3>. A std::array<int, 4> will not compile here.
Library declarations
C++
void swap(array& other) noexcept(/* see below */);
Parameters
Parameter
Description
other
Required. Another std::array with the same element type and the same size N. Its contents are exchanged with the array you call swap on.
Return Value
Return Value
Description
void
Nothing is returned. Both arrays are changed.
C++ Examples
Example 1 — Basic swap()
Exchange two small arrays and print both.
C++
#include <array>
#include <iostream>
int main() {
std::array<int, 3> a = {1, 2, 3};
std::array<int, 3> b = {9, 8, 7};
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: 9 8 7
b: 1 2 3
How It Works
Both arrays are std::array<int, 3>, so the swap is allowed.
a.swap(b) moves the values 9 8 7 into a and 1 2 3 into b.
The two loops print the new contents of each array.
Example 2 — Iterators After a Swap
See that an iterator stays with its own array.
C++
#include <array>
#include <iostream>
int main() {
std::array<int, 3> a = {1, 2, 3};
std::array<int, 3> b = {9, 8, 7};
auto it = a.begin();
std::cout << "Before swap: " << *it << '\n';
a.swap(b);
std::cout << "After swap: " << *it << '\n';
return 0;
}
Output
Before swap: 1
After swap: 9
How It Works
it points to the first slot inside a.
The swap copies new values into the slots of a. The slots themselves do not move.
So it still points into a, and it now reads 9, the value that came from b.
Example 3 — Swap Arrays of double
The same function works for any element type, as long as both arrays match.