Overview

The STL <utility> header contains a small number of templates that are used throughout the STL. In particular, it declares the pair<KType, VType> template struct, which is essential when using maps and multimaps, crops up briefly in the context of sets, and also finds many uses in everyday programming, whenever it is useful to treat two

The pair template struct and the make_pair() function

Here is the definition of the pair struct:

template<class KType, class VType>
struct pair
{
    typedef KType first_type;  //Type of key
    typedef VType second_type; //Type of value
    KType first;  //Contains the key
    VType second; //Contains the value
    //Constructors
    pair();                                //1 Default constructor
    pair(const KType& k, const VType& v);  //2 Supply key and value
    template<class A, class B>
    pair(const pair<A, B>& pairObject);    //3 Copy constructor
};

Typical uses for the pair template struct include:

And here is the prototype of the useful generic function make_pair() for creating pairs:

template<class KType, class VType>
pair<KType, VType> make_pair(const KType& k, const VType& v);

Note that both the return value of the function call

make_pair(123, 'A')

and the object created by the constructor call

pair<int, char>(123, 'A')

give the same end result, but the first is shorter, and, one could argue, clearer than the second.

Comparing pair objects

Two pair objects are equal if and only the first components of both objects are equal and the second components of both objects are also equal. A first pair object is less than a second pair object if either of the following conditions is true:

The other relational operators are all defined in terms of these two.

Sample Programs

pair1.cpp | Windows_executable | program_output (text)
Illustrates the default, non-default, and copy constructors of the pair template struct, as well as the make_pair() function.
pair2.cpp | Windows_executable | program_output (text)
Illustrates comparison of pair objects.