函数std :: swap()是C ++标准模板库(STL)中的内置函数,该函数交换两个变量的值。
句法:
swap(a,b)
参数:该函数接受两个必须交换的必需参数a和b。参数可以是任何数据类型。
返回值:该函数不返回任何内容,它交换两个变量的值。
下面的程序说明了swap()函数:
示例一:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a = 10;
int b = 20;
cout << "Value of a before: "<< a << endl;
cout << "Value of b before: "<< b << endl;
// swap values of the variables
swap(a, b);
cout << "Value of a now: "<< a << endl;
cout << "Value of b now: "<< b << endl;
return 0;
}
输出:
Value of a before: 10
Value of b b