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 pair suitable when the values naturally form a small named association.
  • Unlike std::tuple, pair is intentionally specialized for arity two and integrates directly with tuple-like APIs such as get, tuple_size, and tuple_element.
  • pair is 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

MemberTypeMeaning
firstT1The first stored value
secondT2The 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: first is compared before second.
  • get lets pair participate in tuple-like generic code.

# Reference map

AreaKey entries
Construction and mutationpair::pair, pair::operator=, pair::swap
Tuple-like access and algorithmsget, make_pair, std::swap(std::pair), comparison operators
Helper specializationstuple_size<std::pair>, tuple_element<std::pair>, basic_common_reference<std::pair>, common_type<std::pair>, formatter<pair-or-tuple>
Type deductiondeduction 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

DRApplied toBehavior as publishedCorrect behavior
LWG 2796C++98triviality of the destructor of pair was unspecifiedspecified

# See also