C++ utility get function
The ‘get‘ function of <utility> returns either the first or second value of the pair<Tp1,Tp2> object.
There are three types of get function:
Some points to note:
*The functions are all a template functions and the first template argument is of size_t type.
*The syntax of calling the function is get<Val>( Arg ).We can differentiate whether the returned value should be either the first or the second object of the pair<Tp1,Tp2> template by mentioning the value of Val as 0 or 1.
*The return type is a reference of the type as specified by the Val value.If Val is 0 the return reference type is Tp1,if Val is 1 the type is Tp2.
*The argument can be only a pair<Tp1,Tp2> type.
*The only difference between the first and the third version given above is that the 3rd version returned a const reference.
Code example: Using the 1st version
#include <utility> #include <iostream> using namespace std; int main( ) { pait<string , string> pr{ “New” , “Greenford” }; cout<< get<1>(pr) << endl ; get<0>(pr)=”Happy string”; //work fine cout<< get<0>(pr) << endl ; cin.get( ) ; return 0 ; }
Output
Happy string
The second version is only call when you try to move the object instead of trying to copy the object.You can move the object by calling the function std::move.An example is given below.
Code example: Using the second version
#include <utility> #include <iostream> using namespace std; int main( ) { pait<float , char> prM{ 54.5 , ‘G’ }; cout<< get<0>(std::move(pr)) << endl ; //calls the second version get<1>(std::move(prM))=’o’ ; //work fine cout<< get<1>(std::move(pr)) << endl ; //calls the second version cin.get( ) ; return 0 ; }
Output
o