pair operator assignment function


The operator assignment function allows you to assign a pair object to another object.

1 pair& operator=(const pair& p);
2 pair& operator=(pair&& p); noexcept
3 template<typename T1, typename T2>
pair& operator=(const pair<T1, T2>& p);
4 template<typename T1, typename T2>
pair& operator=(pair<T1, T2>&& p);

The last two functions is a template function.More discussion is provided for all the functions below.


pair& operator=(const pair& p);

This function is use when we assign an object to another pair object.

Parameters:
p – The right pair object.

Return type
pair& – A reference to the pair object.

Let’s look at the code example below.

pair<int,char >pr{ 34 , ‘B’ } , pr1 ;

pr1=pr ;

cout<< pr1.first << endl
<< pr1.second ;

Output

34
B






pair& operator=(const pair&& p);

When you try to move the object -or stealing the object- instead of copying the object this function is used.Also use the std::move() function to call this function.

Parameters:
&&p – A lvalue pair object.

Return type
pair& – A reference to the pair object.

Let’s look at the code example given below.

pair<string,double >pr{ “New string” , 23.45 } , pr1 ;

pr1=std::move(pr) ; //move the object

cout<< pr1.first << endl
<< pr1.second ;

Output

New string
23.45



template<typename T1, typename T2>
pair& operator=(const pair<T1, T2>& p);

This function is a templatize version of the first function.The function is only used when the type of the assigned object differs from the left object type.

Parameters:
p – An assigned object.

Return type
pair& – a reference to the object.

The type must be convertible.The type is limited to int,char and float,
you cannot convert string to any other type.So this function will give an
error if you try to convert a string data to any other type.

Code example

pair< int , char > pr{23 , ‘H’ } ;

pair<float , int > pr1 ;

pr1=pr ; ///work fine

cout<< pr1.first ;

pair<string,char > prSC;

prSC=pr ; ///error,cannot convert int to string

Output

23


 


Stop wasting time,earn money($$$) from your website-Join Now!


template<typename T1, typename T2>
pair& operator=(const pair<T1, T2>&& p);

This function replace the second function if you want to move an object and also the type does not match but convertible.

Parameters:
&&p – A lvalue pair object.

Return type
pair& – A reference to the pair object.

Code example

pair<int , double> prID{ 12 , .90 } ;

pair< char , int > prCI ;

prCI=std::move( prID) ; ///work fine

pair<string , int>prSI ;

prSI=std::move( prID ); //error