You are on page 1of 1

STL Utilities Page 1 of 1

C++ Reference Material


STL Utilities

Overview

The STL <utility> header contains a small number of templates that are used throughout the STL. In
the pair<KType, VType> template struct, which is essential when using maps and multimaps, but also fin
everyday programming, whenever it is useful to treat two values as a single unit. Also defined in this hea
ops, which is nested within namespace std and in turn defines the other relational operators in terms of

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:

• Functions that return two values


• STL maps and multimaps, which use pairs to manage their elements, which are key/value pairs
• Any usage that requires combining two items that logically go together to form a "pair" of any kind

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.

http://cs.smu.ca/~porter/csc/ref/stl/utilities.html 9/23/2010

You might also like