C++ Swap Function Explained
In C++, the swap function is used to exchange the values of two variables. Its usage is as follows:
#include <iostream>
using namespace std;
int main() {
int a = 5;
int b = 10;
cout << "Before swap:" << endl;
cout << "a = " << a << ", b = " << b << endl;
swap(a, b);
cout << "After swap:" << endl;
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
In the example above, the swap function is used to exchange the values of variables a and b. After calling the swap function, the value of a becomes 10 and the value of b becomes 5. The swap function is a general function in the C++ standard library, defined in the header file.