I generally use pairs (and tuples) when I need a local package of 2 or more objects.
The primary usecase is for the return type of a function: C++ does not allow returning multiple values, but allows returning a structure with multiple fields. Rather than use output parameters, I prefer using a pair or tuple.
The second usecase is for ad-hoc storage of elements; for example to automagically generate operator<
for
struct A { int a; int b; int c; };
You can write operator<
this way:
bool operator<(A const& left, A const& right) {
return std::tie(left.a , left.b , left.c )
< std::tie(right.a, right.b, right.c);
}
it automagically generates a correct lexicographical order (so many people screw up those operators...).