Question

My impression is that it is always better to define my own struct, such that I can use meaningful field names instead of first and second.

One place where the standard uses std::pair is for accessing elements of std::map. first is the key, and second the value. Would not it be much better to have a specific key_value_pair template, and refer to its fields as key and value instead of first and second? It seems to me that it would make code considerably more readable at no cost.

Était-ce utile?

La solution

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...).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top