赞
踩
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 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 );
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 !
#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;
}
#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;
}
#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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。