C++ <utility> standard header file

The C++ <utility> header file contains templates structure and some other functions which is utilized by the STL containers to carry out various operations.The <utility> header file is especially meant for used by the other headers file.So it supports other C++ features as a general purpose utilities.

Programmer can also use the structure templates declared under this header’s file directly in their program.In fact,knowing how to use the structure-mainly the ‘pair‘ structure- provided in this header file will provide the user with a basic understanding of how the STL containers namely map ,multimap,unordered_map, and unordered_multimap are built ,as these containers use key/value pair to manage their elements.


***The content will be updated constantly.

templates

template<class Tp1 , class Tp2 >struct pair; Manages two objects as a pair.
template<class T>class initializer_list; This class can store indeterminate number of values of the type.

functions

get<val>( ) (C++11) Get either the value of the object in a pair element.
exchange() (C++14) Exchange values in two objects.

Specialization (C++11)

tuple_element

template&amp;lt;class Tp1 , class Tp2&amp;gt;
 struct tuple_element&amp;lt;0, std::pair&amp;gt;Tp1, Tp2&amp;gt;&amp;gt;
 { typedef Tp1 type; };&amp;lt;/strong&amp;gt;

&amp;lt;strong&amp;gt;template&amp;lt;class Tp1 , class Tp2&amp;gt;
 struct tuple_element&amp;lt;1, std::pair&amp;gt;Tp1, Tp2&amp;gt;&amp;gt;
 { typedef Tp2 type; }; 

Each of the template defines a type that is synonyms for the type corresponding to the type of the pair element.

tuple_size

template&amp;lt;typename Tp1, typename Tp2&amp;gt;
 struct tuple_size&amp;lt;std::pair&amp;amp;lt;Tp1, Tp2&amp;gt;&amp;gt;
: public integral_constant&amp;lt;std::size_t, 2&amp;gt; { };

The tuple_size of <utility> header is inherited from the integral_constant structure.The integral_const structure has a static const member data name value.In this specialization the member data value is initialized to 2.


Code example

 #include &amp;lt;utility&amp;gt;
#include &amp;lt;iostream&amp;gt;

using namespace std ;

int main( )
{
pair&amp;lt;int, string &amp;gt; pr{ 45 , “forty-five” };

//using ‘get’ function
cout&amp;lt;&amp;lt; get&amp;lt;0&amp;gt;(pr) &amp;lt;&amp;lt; endl; //get the first value of pr

//using ‘exchange’ function
exchange( pr.first , 4500 ) ; //exchange the first value of pr
cout&amp;lt;&amp;lt; get&amp;lt;0&amp;gt;(pr) &amp;lt;&amp;lt; endl;

cin.get( ) ;
return 0 ;
}

Output

45
4500




Leave a Reply

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