function template
C++98: <algorithm>, C++11: <utility>
std::swap
// defined in <algorithm> before C++11
template <class T> void swap (T& a, T& b);
non-array (1) |
template <class T> void swap (T& a, T& b)
noexcept (is_nothrow_move_constructible<T>::value && is_nothrow_move_assignable<T>::value);
|
---|
array (2) |
template <class T, size_t N> void swap(T (&a)[N], T (&b)[N])
noexcept (noexcept(swap(*a,*b))); |
---|
Exchange values of two objects
Exchanges the values of a and b.
Before C++11, this function was defined in header
<algorithm>
.
The behavior of this function template is equivalent to:
1 2 3 4
|
template <class T> void swap ( T& a, T& b )
{
T c(a); a=b; b=c;
}
|
Notice how this function involves a copy construction and two assignment operations, which may not be the most efficient way of swapping the contents of classes that store large quantities of data, since each of these operations generally operate in linear time on their size.
Large data types can provide an overloaded version of this function optimizing its performance. Notably, all
standard containers specialize it in such a way that only a few internal pointers are swapped instead of their entire contents, making them operate in constant time.
The behavior of these function templates is equivalent to:
1 2 3 4 5 6 7 8
|
template <class T> void swap (T& a, T& b)
{
T c(std::move(a)); a=std::move(b); b=std::move(c);
}
template <class T, size_t N> void swap (T &a[N], T &b[N])
{
for (size_t i = 0; i<N; ++i) swap (a[i],b[i]);
}
|
Many components of the standard library (within std) call swap in an unqualified manner to allow custom overloads for non-fundamental types to be called instead of this generic version: Custom overloads of swap declared in the same namespace as the type for which they are provided get selected through argument-dependent lookup over this generic version.
Parameters
- a, b
- Two objects, whose contents are swapped.
Type T shall be copy-constructible and assignable.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
// swap algorithm example (C++11)
#include <iostream> // std::cout
#include <utility> // std::swap
int main () {
int x=10, y=20; // x:10 y:20
std::swap(x,y); // x:20 y:10
int foo[4]; // foo: ? ? ? ?
int bar[] = {10,20,30,40}; // foo: ? ? ? ? bar: 10 20 30 40
std::swap(foo,bar); // foo: 10 20 30 40 bar: ? ? ? ?
std::cout << "foo contains:";
for (int i: foo) std::cout << ' ' << i;
std::cout << '\n';
return 0;
}
|
Output:
foo contains: 10 20 30 40
|
Complexity
Non-array: Constant: Performs exactly one construction and two assignments (although notice that each of these operations works on its own complexity).
Array: Linear in N: performs a swap operation per element.
Data races
Both a and b are modified.
See also
- copy
- Copy range of elements (function template
)
- fill
- Fill range with value (function template
)
- replace
- Replace value in range (function template
)