Section
std::pair
std::pair stores exactly two values, first and second, as one object.
# Semantics
pair<T1, T2>is the two-element building block in the tuple family: fixed size, heterogeneous, and value-oriented.- The two elements are named members, not positional access only, which makes
pairsuitable when the values naturally form a small named association. - Unlike std::tuple,
pairis intentionally specialized for arity two and integrates directly with tuple-like APIs such as get,tuple_size, andtuple_element. pairis commonly used for return values, map-like key/value objects, and algorithms that naturally produce two related results.
Use pair when the two-field grouping is obvious and stable. If the object needs domain-specific meaning, a named struct is often clearer.
# Declarations
template< class T1, class T2 >
struct pair;
# Member objects
| Member | Type | Meaning |
|---|---|---|
first | T1 | The first stored value |
second | T2 | The second stored value |
# Example
#include <iostream>
#include <string>
#include <utility>
std::pair<std::string, int> describe()
{
return {"apples", 3};
}
int main()
{
auto [name, count] = describe();
std::cout << name << ": " << count << '\n';
}
This is the common pattern: bundle two related results together, then unpack them with structured bindings or get.
# Operational notes
- Construction and assignment are covered by pair::pair and pair::operator=.
- swap exchanges the two element values with another pair of the same type.
- make_pair is useful when you want type deduction without spelling
pair<T1, T2>explicitly. - comparison operators compare pairs lexicographically:
firstis compared beforesecond. - get lets
pairparticipate in tuple-like generic code.
# Reference map
| Area | Key entries |
|---|---|
| Construction and mutation | pair::pair, pair::operator=, pair::swap |
| Tuple-like access and algorithms | get, make_pair, std::swap(std::pair), comparison operators |
| Helper specializations | tuple_size<std::pair>, tuple_element<std::pair>, basic_common_reference<std::pair>, common_type<std::pair>, formatter<pair-or-tuple> |
| Type deduction | deduction guides |
# Notes
If neither T1 nor T2 is a possibly cv-qualified class type with a non-trivial destructor, or an array of such a type, the destructor of pair is trivial.
# Defect reports
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| LWG 2796 | C++98 | triviality of the destructor of pair was unspecified | specified |