function template
C++98: <algorithm>, C++11: <utility>
std::swaptemplate <class T> void swap (T& a, T& b);header
// moved from <algorithm> to <utility> in C++11non-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.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.
This function is no longer defined in header
<algorithm>
, but in
<utility>
.
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]);
}
Type T shall be copy-constructible and assignable.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// swap algorithm example (C++98)
#include <iostream> // std::cout
#include <algorithm> // std::swap
#include <vector> // std::vector
int main () {
int x=10, y=20; // x:10 y:20
std::swap(x,y); // x:20 y:10
std::vector<int> foo (4,x), bar (6,y); // foo:4x20 bar:6x10
std::swap(foo,bar); // foo:6x10 bar:4x20
std::cout << "foo contains:";
for (std::vector<int>::iterator it=foo.begin(); it!=foo.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
foo contains: 10 10 10 10 10 10
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4