skip to content

Pairs, Tuples and Bindings

std::pair and std::tuple group values without a named struct, and structured bindings unpack them. Interviewers ask how std::tie compares and when a struct is clearer.

on this pageshow

explore

questions

5

In C++, how do you read the elements of a std::pair and a std::tuple, and when does std::get by type fail to compile?

level: juniorimportance: must knowfreq 62%

answer

  1. named members versus positions
  2. first and second
  3. a constant index inside the angle brackets
  4. by type: the type must be unique
  5. mistakes fail at compile time

basics

~20 s

A std::pair has the members first and second; a std::tuple is read with std::get<0>(t) or, since C++14, std::get<T>(t). Both resolve at compile time: an index past the end, or a type that occurs twice, does not compile.

solid answer

~40 s

`std::pair<T1, T2>` has two public data members, `first` and `second`. `std::tuple<Types...>` holds any number of elements but names none of them, so element `I` is read with `std::get<I>(t)`, where `I` is a template argument and therefore a constant expression; a loop variable cannot be used. Since C++14, `std::get<T>(t)` also selects by type, but the standard mandates that `T` occur exactly once among the element types, so `std::get<int>` on a `std::tuple<int, int, double>` is a compile error, just like an index past the end. `std::get` also works on `std::pair` and `std::array`, `std::tuple_size_v` gives the element count, and every overload returns a reference, so `std::get<0>(t) = 404;` writes into the tuple.

code

cpp · 22 lines
cpp
#include <iostream>
#include <string>
#include <tuple>
#include <utility>

int main() {
    std::pair<int, std::string> reply{200, "ok"};
    std::cout << reply.first << ' ' << reply.second << '\n';

    std::tuple<int, std::string, double> result{200, "body", 12.5};
    std::cout << std::get<0>(result) << ' '            // by index
              << std::get<std::string>(result) << ' '  // by type: string occurs once
              << std::get<2>(result) << '\n';

    std::get<0>(result) = 404;                         // get returns a reference
    std::cout << std::get<int>(result) << ' '
              << std::tuple_size_v<decltype(result)> << '\n';

    std::cout << std::get<int>(reply) << '\n';         // get works on pair too
    // std::get<double>(std::tuple<int, int, double>{}) is fine;
    // std::get<int>(std::tuple<int, int, double>{}) does not compile.
}

go deeper

for a junior

Recall first and second on a pair, std::get with an index or a type on a tuple, and that both are checked by the compiler.

for a middle

Explain why the index must be a constant expression, what the exactly-once rule for get by type protects against, and that get returns a reference.

for a senior

Show where positional access hurts readability in a real code base and when you would replace a tuple with a named struct at an API boundary.

for a principal

Weigh tuples in generic plumbing against named types in public interfaces, and set a review rule for where std::get<N> is acceptable.

## Two types for grouping values without a struct The standard library offers two class templates for bundling values that have no type of their own: - **`std::pair<T1, T2>`** holds exactly two values in two public data members called `first` and `second`. It is what `std::map` stores per element and what `std::minmax` returns. - **`std::tuple<Types...>`** holds any number of values, including zero, and gives them **no names at all**. You address an element by its position, or by its type when that type is unique. | | `std::pair<T1, T2>` | `std::tuple<Types...>` | |---|---|---| | Element count | always 2 | any, fixed at compile time | | Named access | `p.first`, `p.second` | none | | Positional access | `std::get<0>(p)`, `std::get<1>(p)` | `std::get<I>(t)` | | Access by type (C++14) | `std::get<T>(p)` | `std::get<T>(t)` | | Factory | `std::make_pair` | `std::make_tuple` | ## Reading an element by index `std::get<I>(t)` is a **function template whose index is a template argument**. Three consequences follow: 1. `I` must be a **constant expression**. `std::get<i>(t)` with a runtime `int i` does not compile, because each index selects a different return type. Visiting every element is done with `std::apply` and a generic lambda, or with an index sequence, not with a `for` loop. 2. An index past the end is a **compile error**, not an exception and not undefined behaviour. With Apple clang 21 and libc++, `std::get<2>` on a two-element tuple fails with "a parameter pack may not be accessed at an out of bounds index". 3. `std::get` returns a **reference** whose value category follows the tuple: `T&` for an lvalue tuple, `const T&` for a const one and `T&&` for an rvalue. Writing `std::get<0>(t) = 404;` therefore changes the tuple itself, and `std::get<1>(std::move(t))` lets you move an element out. ## Reading an element by type, and the uniqueness rule C++14 added `std::get<T>(t)`, which picks the element whose type is `T`. It reads better than an index when the types are distinct, for example `std::get<std::string>(result)`. The standard states the condition as a **Mandates** clause: the type `T` **occurs exactly once** in `Types`. If it occurs twice, or not at all, the program is ill-formed and the compiler must diagnose it. libc++ reports the duplicate case as "type occurs more than once in type list". The rule is exact-type matching, so `std::get<const int>` does not find a plain `int` element, and nothing converts for you. The same by-type overloads exist for `std::pair`, so `std::get<int>(reply)` works on a `std::pair<int, std::string>`; they fail for a `std::pair<int, int>` for the same reason. ## Building pairs and tuples - **`std::make_pair(a, b)`** and **`std::make_tuple(a, b, c)`** deduce the element types from the arguments after decaying them: a string literal becomes `const char*`, and a `std::reference_wrapper` produced by `std::ref` becomes a real reference element. - **Class template argument deduction** (C++17) lets you write `std::pair p{200, 12.5};` or `std::tuple t{1, 2.0};` without the factories. - **`std::tuple_size_v<T>`** and **`std::tuple_element_t<I, T>`** report the element count and the type of element `I` at compile time; they work for `std::pair` and `std::array` as well. ## Why compile-time access matters Because every lookup is resolved during compilation, reading a tuple element costs no more than reading a struct member: there is no index check, no hash, and no type tag. The price is that the code must know positions or types statically. That is why tuples shine in generic code, and why interviewers follow up by asking when a named struct would be clearer, since `std::get<2>(result)` says nothing about what element 2 means. A common junior slip is to assume `std::get` behaves like `std::vector::at` and throws `std::out_of_range`. It cannot: an invalid index never reaches run time. Another is to expect `std::get<int>` to "return the first `int`" in a tuple with two of them; the standard deliberately refuses to guess. ## Reading several elements at once Calling `std::get` three times to pull three elements out is noisy. Two tools do it in one statement: - **Structured bindings** (C++17), `auto [status, payload, latency] = result;`, declare new names for all the elements at once and work on `std::pair`, `std::tuple` and `std::array` alike. - **`std::tie`**, `std::tie(status, std::ignore, latency) = result;`, assigns the elements to variables that already exist, with `std::ignore` absorbing the ones you do not need. Both are positional, exactly like `std::get<I>`, so they inherit the same weakness: nothing in the code says what element 1 means. Interviewers often use that as the bridge to the question of when a named struct should replace the tuple.

  • Can you read element i of a std::tuple when i is only known at run time?
    Not with `std::get`, whose index is a template argument and must be a constant expression, because each element may have a different type and the return type must be fixed at compile time. To touch every element, use `std::apply` with a generic lambda and a fold expression. To pick one at run time, you would have to switch over the indices yourself and produce a common type, such as a `std::variant`.
  • What element types does std::make_pair(1, "x") produce, and why?
    `std::pair<int, const char*>`. `std::make_pair` declares its result as `pair<unwrap_ref_decay_t<T1>, unwrap_ref_decay_t<T2>>`, so each argument is decayed: the string literal's array type decays to a pointer, and cv-qualifiers and references are dropped. Only a `std::reference_wrapper` from `std::ref` or `std::cref` turns into a reference element.

  • std::get<i>(t) accepts an index computed at run time
  • std::get<int> returns the first int when the tuple holds two
  • std::get with a bad index throws std::out_of_range
  • a std::tuple has first and second members like a pair
  • std::get returns a copy, so assigning to it leaves the tuple unchanged
open as a page

Which three kinds of types can a C++ structured binding unpack, and what does each kind require of the type?

level: middleimportance: must knowfreq 60%

basics

~20 s

Structured bindings unpack arrays by element, tuple-like types through std::tuple_size, std::tuple_element and get<i>, and other classes through their non-static data members, which must be accessible and declared in one class. The number of names must match.

open as a page

In C++17, how does std::apply call a function with a tuple's elements, and why does passing an overloaded function name fail?

level: middleimportance: should knowfreq 35%

basics

~20 s

std::apply(f, t) calls f with get<0>(t), get<1>(t) and so on, expanded from an index sequence. An overloaded function name has no single type, so apply's callable parameter cannot be deduced; wrap the call in a lambda.

open as a page

When should a C++ function return a named struct instead of a std::tuple such as std::tuple<int, std::string, double>?

level: middleimportance: should knowfreq 50%

basics

~20 s

Return a named struct whenever callers will read the fields by meaning: status, payload and latencyMs say what get<0>, get<1> and get<2> do not. Structs still unpack with structured bindings; keep tuples for generic code that builds or forwards values by position.

open as a page

How does std::tie give a C++ Version struct a lexicographic operator<, and what does C++20's defaulted operator<=> change?

level: seniorimportance: should knowfreq 45%

basics

~20 s

std::tie builds tuples of references to the members, and tuple comparison is lexicographic, so tie(a.major, a.minor) < tie(b.major, b.minor) compares in order without copying. C++20 replaces the idiom with a defaulted operator<=> that compares members in declaration order.

open as a page