Chuyển đến nội dung

Bài 102 · The Standard Library (STL)

std::pair and std::tuple

Learn C++ std::pair and std::tuple - creating them, structured bindings, std::get, std::tie and std::ignore, std::apply, comparisons, and when a named struct is clearer.

Sometimes you need to bundle two or three values together without the ceremony of declaring a new type: a function that returns a minimum and a maximum, a map entry with its key and value, a coordinate used as a key. The standard library offers two ready-made bundles: std::pair (header <utility>) holds exactly two values, and std::tuple (header <tuple>) holds any fixed number of values of any types.

You've already met pairs without being introduced: every element of a std::map is a std::pair<const Key, T>, and insert returns a std::pair<iterator, bool>. In this lesson you'll learn to create pairs and tuples (and avoid a deduction trap), unpack them with structured bindings and std::tie, access tuple elements by index and by type, call functions with std::apply, use them for comparisons, and, just as importantly, recognize when a small named struct would make your code clearer.

std::pair

A std::pair<T1, T2> is a simple struct with two public members, first and second. You can create one in several ways:

C++
std::pair<std::string, int> a{"apples", 12};   // explicit types
std::pair b{3.5, 'x'};                         // C++17 CTAD: pair<double, char>
auto c = std::make_pair(10, true);             // pair<int, bool>

Pairs compare lexicographically: first by first, and only if those are equal, by second. That's why a vector of pairs sorts naturally by the first component, then the second. Pairs also support ==, <=> (C++20), swap, and copying and moving.

C++ Pairs and where you meet them

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The last two lines show a common surprise. With class template argument deduction (CTAD), std::pair guess{1, "one"} deduces std::pair<int, const char*>: a pointer (8 bytes), not a std::string (32 bytes with GCC). std::make_pair behaves the same. When you want a std::string, spell out the types, or write "one"s with using namespace std::string_literals;.

Structured bindings

A structured binding (C++17) declares several names at once and binds them to the parts of a pair, tuple, struct or array:

C++
auto [name, count] = item;          // copies item, names its parts
auto& [name_ref, count_ref] = item; // refers to item's parts
const auto& [k, v] = *map_iter;     // read-only, no copy

The binding is really one hidden variable (a copy of the source with auto, a reference with auto&) and the names refer to its members. So whether modifications reach the original depends on that auto, auto& or const auto&:

C++ Structured bindings by value and by reference

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Rules worth knowing:

  • The number of names must match the number of elements exactly. To ignore one, you still give it a name; mark the declaration [[maybe_unused]] to silence unused-variable warnings. (C++26 lets you use _ as a placeholder name several times; that's not something to rely on yet.)
  • You can't give the individual names types, and before C++20 lambdas couldn't capture them.
  • Structs work when all non-static data members are public and declared in the same class.

std::tuple

A std::tuple<Types...> generalizes a pair to any number of elements. Since its members have no names, you access them with std::get:

  • std::get<0>(t) gets the element at index 0. The index must be a compile-time constant.
  • std::get<double>(t) gets the element of type double, which compiles only if exactly one element has that type.

Several helpers work with tuples as a whole: std::tuple_size_v<T> is the number of elements, std::tuple_element_t<I, T> is the type of element I, std::tuple_cat joins tuples, and std::apply(f, t) calls f with the tuple's elements as separate arguments.

C++ Creating, reading and applying tuples

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

std::apply shines in generic code, for example to call a function with arguments that were stored earlier. Tuples compare lexicographically just like pairs, element by element.

std::tie and std::ignore

std::tie(a, b, c) creates a tuple of references to existing variables. Assigning a tuple (or pair) to it unpacks the values into those variables. Unlike a structured binding, it doesn't declare new names, so it can update variables that already exist, including in a loop. Put std::ignore in any position you don't care about.

std::tie is also the classic way to write a correct lexicographic comparison by hand: tie the members in priority order and compare the tuples.

C++ std::tie for unpacking and comparing

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The comparator swaps a and b for the version fields (newest first) but not for the name (alphabetical), a common trick for mixed directions. In C++20 code, prefer a defaulted operator<=> when the natural order is simply "member by member": it does the same job with no chance of forgetting a field.

Since C++17, structured bindings replace most uses of std::tie for new variables: auto [major, minor, text] = parse_version("3.14");. Keep std::tie for assigning to existing variables and for std::ignore.

When a struct is clearer

Pairs and tuples are convenient, but their members have no meaningful names. Compare these two function signatures:

C++
std::tuple<double, double, int> analyze(const std::vector<double>& data);

struct Stats {
    double mean;
    double stddev;
    int outliers;
};
Stats analyze(const std::vector<double>& data);

With the tuple, every caller must remember that element 0 is the mean and element 1 the standard deviation, and swapping them compiles without complaint. The struct documents itself (stats.mean), and it still works with structured bindings: auto [mean, stddev, outliers] = analyze(data);. Since C++20, you can even initialize it with designated initializers: Stats{.mean = 2.5, .stddev = 0.4, .outliers = 1} (see Structs, Aggregates and Unions).

C++ The same result as a tuple and as a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

A practical rule of thumb:

  • Use a pair when the two values have an obvious relationship that the context makes clear: key and value, minimum and maximum, a result and a success flag.
  • Use a tuple in generic code (templates, std::apply, storing argument packs) and for quick local groupings that never leave a function.
  • Use a struct for anything in a public interface, anything with three or more members, or anything that will grow. Names are documentation that the compiler checks.

Two more practical notes: neither std::pair nor std::tuple has a standard hash, so they need a custom hasher as keys of unordered containers (see std::unordered_map); and returning several values by struct or tuple is efficient, thanks to copy elision (see Returning Values).

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. std::pair p{2, "two"}; What is the type of p.second?

    Class template argument deduction decays the string literal to const char*. Write std::pair<int, std::string> to get a std::string.
  2. 2. std::pair<std::string, int> p{"a", 1}; auto [s, n] = p; n = 5; What is p.second afterwards?

    With plain auto, the structured binding refers to a hidden copy of p. Use auto& to bind to p itself.
  3. 3. Which statement about std::get on a tuple is correct?

    Indexes must be compile-time constants, and access by type requires that type to appear exactly once. std::get returns a reference, so assignment works.
  4. 4. What does std::tie(a, b) = std::pair{b, a + b}; do when a is 3 and b is 5?

    The right side is evaluated first into a temporary pair {5, 8}; then tie, a tuple of references to a and b, assigns those values to them.
  5. 5. A function returns the mean, the median and the mode of some data. What is the clearest return type for a public API?

    Three doubles in a tuple are easy to mix up and nothing catches it. A struct names each value and still supports structured bindings.

Summary

  • std::pair holds two values (first, second); std::tuple holds any fixed number. Both compare lexicographically and support copying, moving, swap and C++23 formatting.
  • CTAD and std::make_pair decay string literals to const char*; spell out std::string when you need it.
  • Structured bindings (auto, auto&, const auto&) unpack pairs, tuples, structs and arrays; the auto part decides whether you get a copy or a reference.
  • Access tuple elements with std::get<I> or std::get<T>; inspect them with tuple_size_v and tuple_element_t; call functions with std::apply; join with std::tuple_cat.
  • std::tie assigns into existing variables (with std::ignore for skipped slots) and builds member-by-member comparisons.
  • Prefer a named struct for public interfaces and anything with three or more fields; pairs and tuples are best for obvious pairs and generic code.

Next: std::optional, std::variant, std::any and std::expected, the vocabulary types for "maybe a value", "one of several types" and "a value or an error".

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.