std::pair
C++ allows us to pair values, which often comes in handy in programming.
We'll cover the following
With std::pair
, we can build pairs of arbitrary types. The class template std::pair
needs the header <utility>
. std::pair
has a default, copy, and move constructor. Pair objects can be swapped: std::swap(pair1, pair2)
.
Pairs are used in the C++ library. For example, the function std::minmax
returns its result as a pair and the associative containers std::map
, std::unordered_map
, std::multimap
, and std::unordered_multimap
manage their key/value association in pairs.
To get the elements of a pair p
, we can either access them directly or via an index. So, with p.first
or std::get<0>(p)
we get the first element of the pair, and with p.second
or std::get<1>(p)
, we get the second element of the pair.
Pairs support the comparison operators ==
, !=
, <
, >
, <=
, and >=
. If we want to know if two pairs are identical, first the members pair1.first
and pair2.first
will be compared, followed by pair1.second
and pair2.second
. The same strategy holds true for the other comparison operators.
std::make_pair #
C++ has the practical help function std::make_pair
to generate pairs, without specifying their types, since the function will automatically deduce their types.
Let’s take a look at an example:
Get hands-on with 1400+ tech skills courses.