What is the usage of the swap function in C++?
In C++, the swap function is used to exchange the values of two variables. It takes two parameters, passes the addresses of the variables by reference, and then exchanges their values.
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
Simply pass the two variables to be swapped as parameters when calling the swap function.
int a = 5;
int b = 10;
swap(a, b);
In the example above, after calling the swap function, the value of variable a becomes 10 and the value of variable b becomes 5.
In addition to a custom swap function, the C++ standard library also provides a swap function in the header file. It can be used to exchange the values of variables of various types. The method of using the standard library’s swap function is as follows:
#include <algorithm>
using namespace std;
int a = 5;
int b = 10;
swap(a, b);
The effect of using the standard library’s swap function is the same as using a custom swap function.