Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it good to use std::pair?

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.

like image 792
Rémi Avatar asked Oct 29 '13 10:10

Rémi


People also ask

What is std :: pair used for?

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.

When should I use pair C++?

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.

Are vectors faster than pairs C++?

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.

Is std :: pair contiguous?

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.


1 Answers

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

like image 117
Matthieu M. Avatar answered Oct 04 '22 14:10

Matthieu M.