C++ Utility 库 - swap 函数
描述
它交换 a 和 b 的值。
声明
以下是 std::swap 函数的声明。
template <class T> void swap (T& a, T& b);
C++11
template <class T> void swap (T& a, T& b) noexcept (is_nothrow_move_constructible<T>::value && is_nothrow_move_assignable<T>::value);
参数
a, b − 这是两个对象。
返回值
none
异常
Basic guarantee − 如果类型 T 的构造或赋值抛出。
数据竞争
a 和 b 都被修改了。
示例
在下面的示例中解释了 std::swap 函数。
#include <iostream>
#include <utility>
int main () {
int foo[4];
int bar[] = {100,200,300,400};
std::swap(foo,bar);
std::cout << "foo contains:";
for (int i: foo) std::cout << ' ' << i;
std::cout << '\n';
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
foo contains: 100 200 300 400

