Keywords: ISO C++, library

Pairs
Prev | Chapter 6. Utilities | Next

## Pairs

The `pair<T1,T2>` is a simple and handy way to carry around a pair of objects. One is of type T1, and another of type T2; they may be the same type, but you don't get anything extra if they are. The two members can be accessed directly, as `.first` and `.second`.

Construction is simple. The default ctor initializes each member with its respective default ctor. The other simple ctor,

        pair (const T1& x, const T2& y);

does what you think it does, `first` getting `x` and `second` getting `y`.

There is a constructor template for copying pairs of other types:

        template <class U, class V> pair (const pair<U,V>& p);

The compiler will convert as necessary from U to T1 and from V to T2 in order to perform the respective initializations.

The comparison operators are done for you. Equality of two `pair<T1,T2>`s is defined as both `first` members comparing equal and both `second` members comparing equal; this simply delegates responsibility to the respective `operator==` functions (for types like MyClass) or builtin comparisons (for types like int, char, etc).

The less-than operator is a bit odd the first time you see it. It is defined as evaluating to:

        x.first  <  y.first  ||
    	( !(y.first  <  x.first)  &&  x.second  <  y.second )

The other operators are not defined using the `rel_ops` functions above, but their semantics are the same.

Finally, there is a template function called `make_pair` that takes two references-to-const objects and returns an instance of a pair instantiated on their respective types:

        pair<int,MyClass> p = make_pair(4,myobject);

Prev | Up | Next
Chapter 6. Utilities | Home | Memory