C++ pair swap member function
The C++ swap member function of the pair template exchanges data with the other pair object passed as argument. Include the <utility> header to use this function.
void swap(pair & p); |
---|
Parameters:
p – The object whose data is to be exchanged with.
Return type
void
The type of the pair object must match else swapping cannot be performed.This function does not throw exception.
#include <iostream> #include <utility> using namespace std ; int main( ) { pair<float,char>prFc{34.53 , ‘B’} , prFc1 ; prFc.swap(prFc1) ; /** or *** swap(prFc,prFc1); ///work fine,calls the non-member version **/ cout<< prFc.first << ” ” << prFc.second << endl ; cout<< prFc1.first << ” ” << prFc1.second; return 0; }
Output,
0
34.53 B
34.53 B
The value of prFc.second is a blank character.
Here is another example.
pair<float, float>p1 {34.67 , 8901} , p2(90.3 , 188) ; pair< float, string> pnew(34 , "Thirty-four"); p1.swap(p2) ; //p1.swap(pnew)/Error!! cout<< p1.first << " " << p1.second << endl ; cout<< p2.first << " " << p2.second ;
Output,
90.3 188
34.67 8901
34.67 8901