C++ Reference ยท Algorithms
C++ std::swap, iter_swap and swap_ranges
Reference for std::swap, std::iter_swap and std::swap_ranges: exchanging values, elements behind iterators and whole ranges, plus the using std::swap idiom.
std::swap(a, b) exchanges the values of two objects. It is one of the most used functions in C++: sorting algorithms, std::vector::swap, the copy-and-swap idiom and many operator= implementations are built on it. The default version lives in <utility> (and is declared in <algorithm> for older code) and works for any type that is move-constructible and move-assignable. It is also constexpr since C++20.
Two relatives work on iterators: std::iter_swap(it1, it2) swaps the elements the iterators point to, and std::swap_ranges(first1, last1, first2) swaps a whole range with another range of the same length.
int a = 1, b = 2; std::swap(a, b); // a == 2, b == 1 std::iter_swap(v.begin(), v.end() - 1); // swap first and last element std::swap_ranges(x.begin(), x.end(), y.begin());
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Syntax
template<class T> constexpr void std::swap(T& a, T& b) noexcept(/* see below */); template<class T, size_t N> constexpr void std::swap(T (&a)[N], T (&b)[N]); template<class It1, class It2> constexpr void std::iter_swap(It1 a, It2 b); template<class It1, class It2> constexpr It2 std::swap_ranges(It1 first1, It1 last1, It2 first2); // C++17: parallel version with an execution policy
| Name | Description |
|---|---|
a, b |
The objects to exchange (non-const lvalues). For arrays, both must have the same type and size. |
it1, it2 |
Iterators to the elements to exchange; they may point into different containers. |
first1, last1 |
The first range, [first1, last1). |
first2 |
Start of the second range, which must hold at least as many elements. |
Returns: swap and iter_swap return void; swap_ranges returns an iterator to the element one past the last swapped one in the second range.
Errors / undefined behavior: the ranges given to swap_ranges must not overlap, and the second must be long enough, otherwise the behavior is undefined.
Usage notes
- Default behavior. The generic
std::swapis three moves: it movesainto a temporary,bintoa, then the temporary intob. It isnoexceptwhen the type's move constructor and move assignment are. - Containers swap in O(1) (for
std::arrayin O(n)).v.swap(w)andstd::swap(v, w)exchange internal pointers forvector,string,mapand friends, so no elements move. Iterators and references generally stay valid and now refer to the other container. - The
using std::swap;idiom. In generic code callswap(a, b)unqualified afterusing std::swap;. That lets argument-dependent lookup find a betterswapforTand falls back to the standard one. Writingstd::swap(a, b)directly always picks the generic version. std::ranges::swap(C++20) does that lookup for you and is the right customization point when you need it in constrained code.- Write a custom
swaponly for types that manage resources where a cheaper exchange exists, and mark itnoexcept. Anoexceptswap is the key to strong exception safety in the copy-and-swap idiom. - Self-swap (
swap(a, a)) is fine for the standard types. iter_swapand proxies. It swaps*aand*b. Forstd::vector<bool>the dereferenced value is a proxy, and the standard library handles it, but it is another reason to avoid that container.std::exchange(header<utility>) is a different tool: it sets a new value and returns the old one, handy in move constructors.