Introduction
Swapping is a simple operation in C++ which basically is the exchange of data or values among two variables of any data type. Considering both the variables are of the same data type.
The function and its working
The swap() function in C++, from the standard library, is a function that directly swaps values between two given variables of the same types.
swap( a , b );
- a and b, both are variables of the same data type.
- We pass both of them to the swap() function and the values at their respective addresses are exchanged among themselves.
The swap() function from the standard library in C++ can swap values
of any data type including int, float, string, etc. and even data
structures like arrays, stacks, and queues, etc.
Now , let’s look at some examples !
Swapping two integer values
#include <iostream>
using namespace std;
int main()
{
int val1 = 2;
int val2 = 5;
swap(val1, val2);
cout<<"New value of val1 = "<<val1<<endl;
cout<<"New value of val2 = "<<val2<<endl;
return 0;
}
Swapping two string objects from the string header file
#include <iostream>
#include <string>
using namespace std;
int main()
{
string string1 = "String 1";
string string2 = "String 2";
swap(string1, string2);
cout<<"New value of string1 = "<<string1<<endl;
cout<<"New value of string2 = "<<string2<<endl;
return 0;
}
Swapping arrays using the swap() function
#include <iostream>
using namespace std;
int main()
{
int array1[3] = {1,2,3};
int array2[3] = {2,4,6};
int i;
swap(array1, array2);
cout<<"New value of array1 = "<<endl;
for(i=0;i<3;i++)
cout<<" "<<array1[i];
cout<<"\nNew value of array2 = "<<endl;
for(i=0;i<3;i++)
cout<<" "<<array2[i];
return 0;
}
References:https://www.journaldev.com/37269/swap-function-in-c-plus-plus