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.
std::pair is a class template that provides a way to store two heterogeneous objects as a single unit. A pair is a specific case of a std::tuple with two elements.
Pair is used to combine together two values that may be of different data types. Pair provides a way to store two heterogeneous objects as a single unit. It is basically used if we want to store tuples.
Swapping 2 vectors will just swap the pointer to the data while std::pair or std:array will have to move/copy each element, which would be costly for large objects. So what you see is not that pair is faster than vector but that pair is faster than vector in that use case.
std::pair is a struct, the standard says the compiler determines the layout though the order must be maintained, so in the instance of std::pair<char,char> your compiler may decide to place 3-byte padding after each char for optimal alignment, so no you can't assume contiguous memory layout - end of story.
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...).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With