Skip to content
Tutorials Center
My learning

Topics

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.

C++
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

C++ Swapping values, elements and ranges

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.

C++ Customizing swap for your own type

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

C++
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::swap is three moves: it moves a into a temporary, b into a, then the temporary into b. It is noexcept when the type's move constructor and move assignment are.
  • Containers swap in O(1) (for std::array in O(n)). v.swap(w) and std::swap(v, w) exchange internal pointers for vector, string, map and 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 call swap(a, b) unqualified after using std::swap;. That lets argument-dependent lookup find a better swap for T and falls back to the standard one. Writing std::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 swap only for types that manage resources where a cheaper exchange exists, and mark it noexcept. A noexcept swap 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_swap and proxies. It swaps *a and *b. For std::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.