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&lt;class Tp1 , class Tp2&gt; struct tuple_element&lt;0, std::pair&gt;Tp1, Tp2&gt;&gt; { typedef Tp1 type; };&lt;/strong&gt; &lt;strong&gt;template&lt;class Tp1 , class Tp2&gt; struct tuple_element&lt;1, std::pair&gt;Tp1, Tp2&gt;&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&lt;typename Tp1, typename Tp2&gt; struct tuple_size&lt;std::pair&amp;lt;Tp1, Tp2&gt;&gt; : public integral_constant&lt;std::size_t, 2&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 &lt;utility&gt; #include &lt;iostream&gt; using namespace std ; int main( ) { pair&lt;int, string &gt; pr{ 45 , “forty-five” }; //using ‘get’ function cout&lt;&lt; get&lt;0&gt;(pr) &lt;&lt; endl; //get the first value of pr //using ‘exchange’ function exchange( pr.first , 4500 ) ; //exchange the first value of pr cout&lt;&lt; get&lt;0&gt;(pr) &lt;&lt; endl; cin.get( ) ; return 0 ; }
Output
45
4500