C++ pair swap member function

The C++ swap member function of the pair template exchange data with the other pair object passed as argument.Include the <utility> header to use this function.

void swap(pair & p);

p – The object whose data is to be exchanged with.

Return type

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;


34.53 B

The value of prFc.second is blank character.

Leave a Reply

Your email address will not be published. Required fields are marked *