Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

C++  Module 5 – Arrays, vectors and aggregate types

std::pair, std::tuple and structured bindings

Group values with std::pair and std::tuple, unpack them with structured bindings, avoid hidden copies in map loops and sort by several keys with std::tie.

  • Beginner
  • 20 minutes
  • Examples run with Clang 21.0.0, GCC 16.2.0 and Python 3.14.8
  • By MySmartCoPilot
Free lesson, Pro answers: 20 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Group related values with std::pair and std::tuple
  • Write structured bindings that unpack pairs, tuples, arrays and structs
  • Avoid the hidden copies of a loop over a std::map
  • Sort records by several keys with std::tie and tuple comparison
  • Choose between a pair, a tuple and a named struct for a result

Before you start

What you’ll learn · Before you start

What you will learn

  • Group related values with std::pair and std::tuple
  • Write structured bindings that unpack pairs, tuples, arrays and structs
  • Avoid the hidden copies of a loop over a std::map
  • Sort records by several keys with std::tie and tuple comparison
  • Choose between a pair, a tuple and a named struct for a result

Before you start

On this page

std::minmax({72, 91, 85, 64}) has two answers, 64 and 91, and a function returns one object. std::pair holds two values, called first and second; std::tuple holds any fixed number of values, each of its own type. Both group values without declaring a struct, which suits short-lived results: a function that returns a name and a score, or an element of a std::map, which is a pair of a key and its value. structured binding: A declaration such as auto [name, marks] = s; (C++17) that gives one name to each element of an array, a tuple-like type or a class whose data members are all public. The names refer to the members of one unnamed variable made from the initialiser: a copy with auto, s itself with auto&., added in C++17, unpack such a group into names in one declaration, auto [name, marks] = record;, and they work for arrays and for structs with public members too. When the values mean something beyond the next line or two, a struct with named members is still the clearer choice.

Below you will see what a structured binding really declares, count the copies that the wrong loop over a map makes, sort records by several keys with std::tie, and try two C++26 additions. Every example runs with Apple clang 21 and GCC 16.

std::pair holds two values

std::pair, from <utility>, is a struct with two public members, first and second, and their types are its template arguments:

pair_basics.cpp C++ · pair_basics.cpp
// std::pair holds two values, called first and second.
#include <algorithm>
#include <map>
#include <print>
#include <string>
#include <type_traits>
#include <utility>

int main() {
    std::pair<std::string, int> top{"Asha", 91};
    std::println("{} scored {}", top.first, top.second);

    std::pair guessed{"Asha", 91};   // the compiler deduces the types from the values
    std::println("pair<const char*, int>: {}", std::is_same_v<decltype(guessed), std::pair<const char*, int>>);

    using namespace std::string_literals;
    std::pair fixed{"Asha"s, 91};    // "Asha"s is a std::string
    std::println("pair<std::string, int>: {}", std::is_same_v<decltype(fixed), std::pair<std::string, int>>);

    std::map<std::string, int> marks{{"Asha", 91}};
    auto result = marks.insert({"Asha", 75});           // insert returns an iterator and a bool
    std::println("inserted: {}, value kept: {}", result.second, result.first->second);

    auto range = std::minmax({72, 91, 85, 64});         // so does std::minmax: the smallest and the largest
    std::println("lowest {}, highest {}", range.first, range.second);
}
Pairs, built and run with both compilers Python · pair_basics_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra pair_basics.cpp -o pair_basics && ./pair_basics
g++-16 -std=c++23 -Wall -Wextra pair_basics.cpp -o pair_basics-gcc && ./pair_basics-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra pair_basics.cpp -o pair_basics && ./pair_basics
Asha scored 91
pair<const char*, int>: true
pair<std::string, int>: true
inserted: false, value kept: 91
lowest 64, highest 91
$ g++-16 -std=c++23 -Wall -Wextra pair_basics.cpp -o pair_basics-gcc && ./pair_basics-gcc
Asha scored 91
pair<const char*, int>: true
pair<std::string, int>: true
inserted: false, value kept: 91
lowest 64, highest 91

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 pair_basics_session.py

Three things are worth noticing in the output:

  • Without template arguments, the compiler type deduction: The compiler working out a type from an initializer or an argument instead of reading it from the declaration, as it does for auto, decltype(auto) and the parameters of function templates. More in “C++ auto, decltype and type aliases” the types from the values, and a string literal: Text in double quotes in the source, such as "pune": an array of const char holding the characters and a terminating '\0', made before the program starts and kept for its whole run. Writing into one is undefined behaviour. More in “C-style strings and why std::string replaced them” such as "Asha" becomes a const char*, not a std::string. Comparing two such pairs compares addresses, not text. Write the types out, or use the s suffix from std::string_literals, which makes "Asha"s a std::string.
  • The standard library returns pairs where it has two results. std::map::insert returns the position of the element and whether it was inserted: here false, because the key "Asha" was already there, so the old value 91 stays.
  • std::minmax returns the smallest and the largest value as a pair, found in one pass.

Pairs compare like words in a dictionary: first decides, and second only when the firsts are equal.

Step through the insert that kept 91, and see the two results it packed into one pair:

Interactive · step by step The pair that std::map::insert hands back Step through one insert into a map that already has the key. The left box is the map, the right ones the call and the pair it returns.
The pair that std::map::insert hands back, step 5 of 5. Showing std::map marks, insert({"Asha", 75}), auto result (first: iterator, second: false), what the program printed (inserted: false, kept: 91). In focus: what the program printed, std::map marks.looks up the keyreturnsfirst points herestd::map marks"Asha" with 91insert({"Asha", 75})a key and a valueauto resultfirst: iterator, second: falsewhat the program printedinserted: false, kept: 91

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. One element per key. marks holds one element, the key "Asha" with the value 91. Each element of a std::map is itself a pair: the key as first, the value as second.
  2. The key is there. insert({"Asha", 75}) first looks for the key. A map keeps one element per key, and "Asha" is already in it.
  3. Nothing is inserted. So insert changes nothing: the old value 91 stays, and the 75 is dropped. insert has two results to report, where the element is and whether it was inserted.
  4. Two results in one pair. It returns both as a std::pair: first is an iterator to the element with that key, second is a bool, false here because nothing was inserted.
  5. Reading the pair. result.second is false, and result.first->second follows the iterator to the element and reads its value. The program printed inserted: false, value kept: 91.

One call, two answers, one object to return: that is the job a pair does all over the standard library.

Checkpoint

Check: std::pair and its two members

  1. Question 1 of 2 With using namespace std::string_literals;, what type does the compiler deduce for std::pair fixed{"Asha"s, 91};?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: std::pair<std::string, int>

    Deduction takes the types from the values. "Asha" is a string literal and becomes const char*, while "Asha"s is a std::string, which compares text instead of addresses.

  2. Question 2 of 2 std::map<std::string, int> marks{{"Dev", 72}}; then auto r = marks.insert({"Asha", 75});. What are r.second and marks.at("Asha")?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: true and 75

    insert returns a pair: an iterator to the element with that key, and a bool that is true when this call inserted it. In pair_basics.cpp the key existed, so it gave false and kept 91; here it is new.

std::tuple holds any number of values

std::tuple, from <tuple>, generalises the pair to any number of elements. There are no member names, so you reach an element by its position with std::get<0>(t), or by its type, std::get<double>(t), when that type occurs only once in the tuple:

tuple_basics.cpp C++ · tuple_basics.cpp
// std::tuple holds a fixed number of values, each with its own type.
#include <print>
#include <string>
#include <tuple>

std::tuple<std::string, int, double> topper() {
    return {"Asha", 12, 91.5};
}

int main() {
    auto t = topper();
    std::println("{} (roll {}): {}", std::get<0>(t), std::get<1>(t), std::get<2>(t));
    std::println("marks, found by type: {}", std::get<double>(t));
    std::println("elements: {}", std::tuple_size_v<decltype(t)>);

    std::string name;
    int roll = 0;
    std::tie(name, roll, std::ignore) = topper();   // assigns to variables that already exist
    std::println("{} has roll number {}", name, roll);
}
A tuple returned from a function Python · tuple_basics_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra tuple_basics.cpp -o tuple_basics && ./tuple_basics
g++-16 -std=c++23 -Wall -Wextra tuple_basics.cpp -o tuple_basics-gcc && ./tuple_basics-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra tuple_basics.cpp -o tuple_basics && ./tuple_basics
Asha (roll 12): 91.5
marks, found by type: 91.5
elements: 3
Asha has roll number 12
$ g++-16 -std=c++23 -Wall -Wextra tuple_basics.cpp -o tuple_basics-gcc && ./tuple_basics-gcc
Asha (roll 12): 91.5
marks, found by type: 91.5
elements: 3
Asha has roll number 12

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 tuple_basics_session.py

std::tuple_size_v gives the number of elements at compile time. std::tie(name, roll, std::ignore) makes a tuple of references to existing variables, so assigning a tuple to it assigns each element to its variable, and std::ignore throws one element away. This was the usual way to unpack a returned tuple before C++17.

Step through that last assignment and watch each element of the returned tuple go to its own reference:

Interactive · step by step Unpacking a tuple with std::tie Step through tuple_basics.cpp. The left boxes are the elements of the tuple topper() returns; the right boxes are what std::tie refers to.
Unpacking a tuple with std::tie, step 6 of 6. Showing element 0: "Asha", element 1: 12, element 2: 91.5, name ("Asha"), roll (12), std::ignore (dropped). In focus: element 2: 91.5, std::ignore.assignedassignedassignedelement 0: "Asha"std::stringelement 1: 12intelement 2: 91.5doublename"Asha"roll12std::ignoredropped91.5

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. Three elements, no names. topper() returns a std::tuple<std::string, int, double> holding "Asha", 12 and 91.5. The elements have no names, only positions 0, 1 and 2; std::tuple_size_v says 3.
  2. By position or by type. std::get<0>(t), std::get<1>(t) and std::get<2>(t) read the elements by position. std::get<double>(t) reads by type, which works because double occurs once: it printed 91.5.
  3. A tuple of references. std::tie(name, roll, std::ignore) makes a tuple of three references: to name, to roll and to std::ignore, an object that accepts any value and keeps nothing. name and roll must already exist.
  4. Element 0. Assigning topper()'s tuple to it assigns element by element, in order. First "Asha" goes into name.
  5. Element 1. Then 12 goes into roll, through the second reference.
  6. Element 2, dropped. Last, 91.5 goes to std::ignore, which drops it. The program printed Asha has roll number 12: two variables set from one returned tuple.

std::ignore took the 91.5 and kept nothing, which is how std::tie skips an element it does not need.

Positions such as std::get<2>(t) say nothing about what the value is, and a reader has to look up the function to learn which element is which. That is the problem structured bindings solve.

Checkpoint

Check: std::tuple, std::get and std::tie

  1. Question 1 of 2 auto t = topper(); holds "Asha", 12 and 91.5, a std::tuple<std::string, int, double>. What is std::get<1>(t)?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: 12

    std::get<i>(t) reads element i, counting from 0: "Asha", 12, 91.5 are at 0, 1 and 2. The program printed them in that order.

  2. Question 2 of 2 After std::tie(name, roll, std::ignore) = topper();, where did 91.5 go?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Nowhere. std::ignore accepts the value and keeps nothing

    std::tie(name, roll, std::ignore) is a tuple of references to name, roll and std::ignore. Assigning the returned tuple to it assigns "Asha" to name and 12 to roll, and drops 91.5.

Structured bindings unpack in one declaration

A structured binding declares a name for every element of an object at once:

bindings.cpp C++ · bindings.cpp
// Structured bindings name each element of a struct, an array or a tuple in one declaration.
#include <print>
#include <string>
#include <tuple>

struct Student {
    std::string name;
    int marks = 0;
};

int main() {
    Student s{"Meera", 85};

    auto [name, marks] = s;            // names for the members of a copy of s
    marks = 50;                        // changes the copy only
    std::println("{}: copy {}, original {}", name, marks, s.marks);

    auto& [same_name, same_marks] = s;   // names for the members of s itself
    same_marks = 95;
    std::println("{}: original now {}", same_name, s.marks);

    int sides[3]{3, 4, 5};
    auto [a, b, c] = sides;            // an array
    std::println("{} + {} > {}: {}", a, b, c, a + b > c);

    auto [who, roll, score] = std::tuple{std::string{"Dev"}, 7, 72.5};   // a tuple
    std::println("{} (roll {}): {}", who, roll, score);
}
Copies, references, an array and a tuple Python · bindings_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra bindings.cpp -o bindings && ./bindings
g++-16 -std=c++23 -Wall -Wextra bindings.cpp -o bindings-gcc && ./bindings-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra bindings.cpp -o bindings && ./bindings
Meera: copy 50, original 85
Meera: original now 95
3 + 4 > 5: true
Dev (roll 7): 72.5
$ g++-16 -std=c++23 -Wall -Wextra bindings.cpp -o bindings-gcc && ./bindings-gcc
Meera: copy 50, original 85
Meera: original now 95
3 + 4 > 5: true
Dev (roll 7): 72.5

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 bindings_session.py

auto [name, marks] = s; does not make two independent variables. It declares one unnamed variable initialised from s, here a copy of it, and makes name and marks names for the members of that unnamed variable. That is why assigning 50 to marks changed the copy and left s.marks at 85. With auto&, the unnamed variable is a reference to s, so same_marks = 95 changed s itself, and const auto& gives read-only names without a copy.

With auto the names refer to members of an unnamed copy of s; with auto& the unnamed variable is a reference to s itself.auto [name, marks] = s;auto& [name, marks] = s;Student sname = "Meera"marks = 85an unnamed copy of sname = "Meera"marks = 85name and marksrefer to its membersan unnamed reference to sname and marksrefer to the members of scopied fromis

What a structured binding declares, with auto and with auto&

Text description of the diagram

The diagram compares two declarations that unpack the same Student s, whose name is "Meera" and whose marks are 85.

  1. auto [name, marks] = s; creates an unnamed variable that is a copy of s. The names name and marks refer to the members of that copy, so changing marks leaves s unchanged.
  2. auto& [name, marks] = s; creates an unnamed reference to s. The names name and marks then refer to the members of s itself, so assigning to marks changes s.

In both cases name and marks are not separate variables of their own: they are names for the members of the unnamed variable.

The diagram shows both declarations side by side. Step through them in the order the program runs them, and watch which object each assignment changes:

Interactive · step by step What auto [name, marks] = s; really declares Step through the first two declarations of bindings.cpp. The left column is s and a reference to it; the right column is the copy that auto makes.
What auto [name, marks] = s; really declares, step 6 of 6. Showing Student s (Meera, marks 95), an unnamed copy of s (Meera, marks 50), name, marks, an unnamed reference, same_name, same_marks. In focus: Student s, same_name, same_marks.copiedrefer torefers torefer toStudent sMeera, marks 95an unnamed copy of sMeera, marks 50name, marksnames for the copy's membersan unnamed referenceit is s itselfsame_name, same_marksnames for the members of s

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. One student. Student s{"Meera", 85}; is an aggregate with two public members, so a structured binding can unpack it.
  2. An unnamed copy. auto [name, marks] = s; first declares one unnamed variable, initialised from s. With plain auto it is a copy of s, with its own name and marks.
  3. Names, not variables. name and marks are not two new variables. They are names for the members of that unnamed copy.
  4. Changing the copy. marks = 50; changes the copy's member, and s is not touched. The program printed Meera: copy 50, original 85.
  5. An unnamed reference. auto& [same_name, same_marks] = s; makes the unnamed variable a reference to s, so nothing is copied, and the two names refer to the members of s itself.
  6. Changing s. same_marks = 95; therefore changes s. The program printed Meera: original now 95. const auto& gives the same names without the copy, read-only.

A structured binding can unpack three kinds of object:

  • an array, such as int sides[3], whose size the compiler knows;
  • a tuple-like type: A type that describes its elements through std::tuple_size, std::tuple_element and get, as std::pair, std::tuple and std::array do. Structured bindings unpack such a type by position, whatever its members are called.: std::pair, std::tuple, std::array, and any type that describes its elements through std::tuple_size, std::tuple_element and get;
  • a class whose non-static data members are all public, such as the aggregates of the previous lesson, with one name per member in declaration order (inside the class’s own member functions, private members count too).

The number of names must equal the number of elements exactly. A std::vector cannot be unpacked, because its size is known only at run time, and outside its own members a class with a private data member cannot either.

Key idea

A structured binding declares one unnamed variable and a name for each of its members: auto makes that variable a copy, auto& a reference, and const auto& a read-only reference.

Checkpoint

Check: What a structured binding declares

  1. Question 1 of 2 After Student s{"Meera", 85}; auto [n, m] = s; m = 50;, what is s.marks?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: 85

    auto [n, m] = s; declares one unnamed copy of s and two names for its members. Assigning through m changes the copy only, so s.marks stays 85.

  2. Question 2 of 2 int sides[3]{3, 4, 5}; Which declaration compiles?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: auto [a, b, c] = sides;

    A structured binding needs a size known while compiling and exactly one name per element. int[3] has three elements, so [a, b, c] fits it; the program printed 3 + 4 > 5: true.

Only the right reference reads a map without copying

A std::map<std::string, Marks> stores its elements as std::pair<const std::string, Marks>: the key is const, so that nobody can change it and break the map’s order. A range-based for: A loop of the form for (declaration : range) that runs its body once for each element of an array, a container or another range, in order, with no index to manage. auto copies each element; auto& refers to it. More in “C++ loops: while, do-while, for and range-for” with structured bindings is the natural way to read them, but the declaration decides whether every element is copied. Marks below counts its own copies:

map_copies.cpp C++ · map_copies.cpp
// How many copies does each loop over a map make? Marks counts every copy of itself.
#include <map>
#include <print>
#include <string>
#include <utility>

struct Marks {
    int value = 0;
    static inline int copies = 0;
    Marks(int v) : value{v} {}
    Marks(const Marks& other) : value{other.value} { ++copies; }
};

int main() {
    std::map<std::string, Marks> marks{{"Asha", 91}, {"Dev", 72}, {"Meera", 85}};
    int total = 0;

    Marks::copies = 0;
    for (auto [name, m] : marks) total += m.value;
    std::println("auto [name, m]                    {} copies", Marks::copies);

    Marks::copies = 0;
    for (const auto& [name, m] : marks) total += m.value;
    std::println("const auto& [name, m]             {} copies", Marks::copies);

    Marks::copies = 0;
    for (const std::pair<std::string, Marks>& p : marks) total += p.second.value;
    std::println("const pair<string, Marks>&        {} copies", Marks::copies);

    Marks::copies = 0;
    for (const std::pair<const std::string, Marks>& p : marks) total += p.second.value;
    std::println("const pair<const string, Marks>&  {} copies", Marks::copies);

    for (auto& [name, m] : marks) m.value += 5;   // the values can change; the keys are const
    std::println("Asha now has {} (the four loops added up {})", marks.at("Asha").value, total);
}
Copies made by four loops over three elements Python · map_copies_session.py
from session import run

# -Wall makes both compilers point at the loop that copies without saying so.
run("""
clang++ -std=c++23 -Wall -Wextra map_copies.cpp -o map_copies && ./map_copies
g++-16 -std=c++23 -Wall -Wextra map_copies.cpp -o map_copies-gcc && ./map_copies-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra map_copies.cpp -o map_copies && ./map_copies
map_copies.cpp:27:47: warning: loop variable 'p' of type 'const std::pair<std::string, Marks> &' (aka 'const pair<basic_string<char>, Marks> &') binds to a temporary constructed from type 'reference' (aka 'pair<const std::string, Marks> &') [-Wrange-loop-construct]
   27 |     for (const std::pair<std::string, Marks>& p : marks) total += p.second.value;
      |                                               ^
map_copies.cpp:27:10: note: use non-reference type 'std::pair<std::string, Marks>' (aka 'pair<basic_string<char>, Marks>') to make construction explicit or type 'const value_type &' (aka 'const pair<const std::string, Marks> &') to prevent copying
   27 |     for (const std::pair<std::string, Marks>& p : marks) total += p.second.value;
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 warning generated.
auto [name, m]                    3 copies
const auto& [name, m]             0 copies
const pair<string, Marks>&        3 copies
const pair<const string, Marks>&  0 copies
Asha now has 96 (the four loops added up 992)
$ g++-16 -std=c++23 -Wall -Wextra map_copies.cpp -o map_copies-gcc && ./map_copies-gcc
map_copies.cpp: In function 'int main()':
map_copies.cpp:27:47: warning: loop variable 'p' of type 'const std::pair<std::__cxx11::basic_string<char>, Marks>&' binds to a temporary constructed from type 'std::pair<const std::__cxx11::basic_string<char>, Marks>' [-Wrange-loop-construct]
   27 |     for (const std::pair<std::string, Marks>& p : marks) total += p.second.value;
      |                                               ^
map_copies.cpp:27:47: note: use non-reference type 'const std::pair<std::__cxx11::basic_string<char>, Marks>' to make the copy explicit or 'const std::pair<const std::__cxx11::basic_string<char>, Marks>&' to prevent copying
auto [name, m]                    3 copies
const auto& [name, m]             0 copies
const pair<string, Marks>&        3 copies
const pair<const string, Marks>&  0 copies
Asha now has 96 (the four loops added up 992)

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 map_copies_session.py

The counts are the same with both compilers:

  • auto [name, m] copies every element, key and value, into the unnamed variable: 3 copies.
  • const auto& [name, m] binds to each element where it is: no copy.
  • const std::pair<std::string, Marks>& looks like a reference, yet copies every element. The element type is a pair with a const std::string, a different type, so the compiler builds a temporary object: An unnamed object made while an expression is evaluated, such as the std::string that city + ' Central' produces. It is destroyed at the end of the full expression that made it, unless a reference bound to it keeps it alive. More in “std::string and std::string_view” pair of the written type for each element and binds the reference to that. Both compilers point at this loop with -Wall (-Wrange-loop-construct).
  • Naming the right type, const std::pair<const std::string, Marks>&, avoids the copy, but const auto& is shorter and cannot get the type wrong.

Step through one pass of that third loop to see where its copies come from:

Interactive · stage by stage Why a reference to the wrong pair copies every element Step through one pass of the third loop of map_copies.cpp, from the element in the map to the reference the loop gets.
Why a reference to the wrong pair copies every element, step 6 of 6. Showing An element of the map, The loop's reference (const auto& [name, m]), Two different types, A temporary pair, The reference binds to it (copies of Marks: 0). In focus: The loop's reference, The reference binds to it.An element of the mappair<const string, Marks>The loop's referenceconst auto& [name, m]Two different typesthe key is const in one onlyA temporary pairconverted from the elementThe reference binds to itcopies of Marks: 0

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. The element type. A std::map<std::string, Marks> keeps each element as std::pair<const std::string, Marks>. The key is const, so that nobody can change it and break the map's order.
  2. The type the loop asks for. The loop declares const std::pair<std::string, Marks>& p: a reference to a pair whose key is not const. It looks like a reference to the element.
  3. Not the same type. pair<std::string, Marks> and pair<const std::string, Marks> are two different types, so the reference cannot refer to the element itself.
  4. A temporary pair. A reference to const may bind to a temporary object, so the compiler builds one for each element: a new pair converted from the element, which copies the key and the Marks.
  5. Three elements, three copies. Asha, Dev and Meera each get their own temporary pair, so Marks counted 3 copies: as many as auto [name, m], which copies on purpose.
  6. The warning, and the fix. -Wall made both compilers point at this loop with -Wrange-loop-construct. const auto& [name, m] cannot get the element type wrong: 0 copies, the same as naming const std::pair<const std::string, Marks>&.

The reference was never the problem; its type was. Letting auto name the type removes the mismatch.

To change the values in place, write auto&: for (auto& [name, m] : marks) m.value += 5; changes the map, while an attempt to assign to name does not compile, because the key is const. With a few strings the copies cost little, but in a loop over a large map of large values they cost real time, and nothing in the code says that they happen.

Key idea

Read a map with const auto& [key, value] and change its values with auto& [key, value]: a type you spell out by hand can miss one const and copy every element.

Checkpoint

Check: Map loops without copies

  1. Question 1 of 2 A std::map<std::string, Marks> has 5 elements. How many copies of Marks does for (const std::pair<std::string, Marks>& p : m) make?

    Type a number.

    A hint

    Compare the reference's pair type with the map's element type.

    Show the answer: Question 1 of 2

    Answer: 5 copies

    The map's elements are std::pair<const std::string, Marks>. The reference asks for a pair with a non-const key, a different type, so the compiler builds a temporary pair from each element: 5 elements, 5 copies, as 3 elements gave 3 in map_copies.cpp.

  2. Question 2 of 2 Inside for (auto& [name, m] : marks), over a std::map<std::string, Marks>, which statement does not compile?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: name = "Zoya";

    A map stores std::pair<const Key, T>. With auto& the names refer to the element itself, so the value can change and the key, being const, cannot.

std::tie sorts by several keys, each in its own direction

Tuples compare lexicographic comparison: Comparing two sequences element by element from the first: the first pair of elements that differ decides, and a sequence that runs out first is the smaller. Tuples, pairs, std::array and strings compare this way, like words in a dictionary.: the first elements decide, and only when they are equal do the second elements, and so on. std::tie(a.marks, a.name) builds a tuple of references to the members, without copying them, so comparing two such tuples compares the records by marks and then by name. Swapping a and b in one position turns that key around:

rank_students.cpp C++ · rank_students.cpp
// Highest marks first, and names from A to Z among equal marks, by comparing std::tie tuples.
#include <algorithm>
#include <print>
#include <string>
#include <tuple>
#include <vector>

struct Student {
    std::string name;
    int marks = 0;
};

int main() {
    std::println("(2, 9) < (3, 0): {}", std::tuple{2, 9} < std::tuple{3, 0});   // first elements decide
    std::println("(3, 1) < (3, 0): {}", std::tuple{3, 1} < std::tuple{3, 0});   // a tie: the second decides

    std::vector<Student> students{{"Kabir", 72}, {"Asha", 91}, {"Dev", 72}, {"Meera", 85}, {"Arjun", 91}};
    std::ranges::sort(students, [](const Student& a, const Student& b) {
        // b's marks against a's: a larger mark sorts first. Then a's name against b's: A to Z.
        return std::tie(b.marks, a.name) < std::tie(a.marks, b.name);
    });
    for (const auto& [name, marks] : students) std::println("{:>3} {}", marks, name);
}
Highest marks first, then names from A to Z Python · rank_students_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra rank_students.cpp -o rank_students && ./rank_students
g++-16 -std=c++23 -Wall -Wextra rank_students.cpp -o rank_students-gcc && ./rank_students-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra rank_students.cpp -o rank_students && ./rank_students
(2, 9) < (3, 0): true
(3, 1) < (3, 0): false
 91 Arjun
 91 Asha
 85 Meera
 72 Dev
 72 Kabir
$ g++-16 -std=c++23 -Wall -Wextra rank_students.cpp -o rank_students-gcc && ./rank_students-gcc
(2, 9) < (3, 0): true
(3, 1) < (3, 0): false
 91 Arjun
 91 Asha
 85 Meera
 72 Dev
 72 Kabir

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 rank_students_session.py

The comparison std::tie(b.marks, a.name) < std::tie(a.marks, b.name) puts b.marks on the left, so a student with more marks sorts first, and keeps a.name on the left, so equal marks fall back to alphabetical order: Arjun before Asha, Dev before Kabir. The previous lesson’s defaulted operator<=> always compares in declaration order, ascending; std::tie lets each sort choose its own keys and directions without changing the struct. It needs named variables or members, though: for a key that is computed, such as a total, build a std::tuple of values instead.

Step through two of the comparisons the sort made, one decided by the names and one by the marks:

Interactive · stage by stage How std::tie decides whether one student sorts first Step through the comparison the sort calls. The boxes run from the two students to the answer; the sub-labels show this step's values.
How std::tie decides whether one student sorts first, step 6 of 6. Showing Does a sort before b? (a: Asha 91, b: Meera 85), tie(b.marks, a.name) ((85, "Asha")), tie(a.marks, b.name) ((91, "Meera")), First elements (85 < 91: decided), Second elements (not needed), The answer (Arjun Asha Meera Dev Kabir). In focus: The answer.Does a sort before b?a: Asha 91, b: Meera 85tie(b.marks, a.name)(85, "Asha")tie(a.marks, b.name)(91, "Meera")First elements85 < 91: decidedSecond elementsnot neededThe answerArjun Asha Meera Dev Kabir

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. Tuples compare in order. Two tuples compare element by element, and the first pair that differs decides: (2, 9) < (3, 0) is true because 2 < 3, and (3, 1) < (3, 0) is false because 3 ties and 1 is not less than 0.
  2. Two tuples of references. The sort asks whether a, Asha with 91, goes before b, Arjun with 91. The lambda builds tie(b.marks, a.name), which is (91, "Asha"), and tie(a.marks, b.name), which is (91, "Arjun"), without copying anything.
  3. The marks tie. 91 against 91 is equal, so the first elements cannot decide and the names are compared next.
  4. The names decide. "Asha" < "Arjun" is false: both start with A, and r comes before s. So left < right is false, and Asha does not go before Arjun.
  5. Marks reversed. Now a is Asha with 91 and b is Meera with 85. Left is (85, "Asha") and right is (91, "Meera"), and 85 < 91 decides at once: true, so Asha sorts first. b's marks on the left put more marks first.
  6. The sorted list. Applied to every pair the sort compares, the rule gives the order the program printed: 91 Arjun, 91 Asha, 85 Meera, 72 Dev, 72 Kabir.

Each key’s direction comes from whose member stands on the left, so one line states both keys and both directions.

Checkpoint

Check: Sorting by several keys with std::tie

  1. Question 1 of 2 What is std::tuple{4, 7, 1} < std::tuple{4, 7, 2}?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: true

    Tuples compare lexicographically: the first pair of elements that differ decides. Here it is the third pair, 1 against 2, so the result is true.

  2. Question 2 of 2 Which comparison sorts students by marks from low to high, and by name from Z to A when the marks are equal?

    Choose one answer.

    A hint

    The side a member is on decides the direction of that key.

    Show the answer: Question 2 of 2

    Answer: std::tie(a.marks, b.name) < std::tie(b.marks, a.name)

    For each key, a's member on the left gives ascending order and b's member on the left gives descending order. Marks ascending puts a.marks left; names descending puts b.name left.

pair, tuple or a named struct?

All three group values, and all three work with structured bindings, so the choice is about the reader:

Choosing a way to group values
Criterion std::pairstd::tupleA struct
Names first, secondPositions: get<0> …Your own
Parts Exactly 2Any fixed numberAny
Compare Built inBuilt inWith = default
Unpack YesYesIf members are public
When to choose A key with its value; library resultsGeneric code; std::tie keysValues with a meaning

The C++ Core Guidelines (rule F.21) prefer a struct for a function that returns several values: Summary with members min, max and mean tells the caller what each value is, and a structured binding unpacks it just as easily as a tuple. Keep pairs and tuples for code that does not know what the values mean, such as templates that handle any number of types, and for keys and results whose meaning is obvious on the spot.

A quick test

If a reader needs the function’s documentation to know what get<1> or second holds, give the values names: write a struct.

The exercise at the end of this lesson returns the same three results both ways, so you can compare the two call sites yourself.

Checkpoint

Check: Pair, tuple or named struct

  1. Question 1 of 2 A function returns the smallest value, the largest and the mean of a list. Following rule F.21 of the C++ Core Guidelines, what should it return?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: A struct Summary with members min, max and mean

    Return a named struct when the values mean something to the caller. A structured binding unpacks it as easily as a tuple, and summarise(marks).mean names what it reads.

  2. Question 2 of 2 A function template must hand back all the values it was given, of any types and any number. Which grouping fits?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: A std::tuple of those types

    Keep tuples for code that does not know what its values mean, such as templates over any number of types, and give results a named struct where the meaning is known.

C++26 adds a placeholder name and binding packs

C++26, whose draft is complete but not yet published as an ISO standard, adds several features to structured bindings, among them these two. Both compilers accept them with -std=c++2c, the option for the C++26 draft:

  • A placeholder, _ (paper P2169R4), names an element you do not need. Unlike an ordinary name, it may appear several times in one declaration: auto [_, physics, _] = scores;. GCC has supported it since version 14 and Clang since version 18.
  • Binding packs (paper P1061R10) give a group of names to “all the remaining elements”: auto [first, ...rest] = value;. A pack works only inside a template, and you use it like any other pack, with sizeof... or a fold expression. GCC 16 and Clang 21 are the first versions with it.
cpp26_bindings.cpp C++ · cpp26_bindings.cpp
// C++26 previews: the placeholder _ and structured binding packs (build with -std=c++2c).
#include <print>
#include <tuple>

struct Scores {
    int maths = 0;
    int physics = 0;
    int chemistry = 0;
};

// A pack, ...parts, gets one name for every element, whatever the type has. Packs work only in templates.
template <class T>
int total(const T& value) {
    const auto& [...parts] = value;
    return (0 + ... + parts);
}

template <class T>
int count_after_first(const T& value) {
    const auto& [first, ...rest] = value;
    (void)first;
    return sizeof...(rest);
}

int main() {
    Scores s{91, 78, 85};
    auto [_, physics, _] = s;   // _ can be repeated: these elements are not needed
    std::println("physics {}", physics);
    std::println("total of a struct {}, of a tuple {}", total(s), total(std::tuple{1, 2, 3, 4}));
    std::println("elements after the first: {}", count_after_first(s));
}
Both compilers in C++26 mode Python · cpp26_bindings_session.py
from session import run

# -std=c++2c is the switch for the C++26 draft in both compilers.
run("""
clang++ -std=c++2c -Wall -Wextra cpp26_bindings.cpp -o cpp26_bindings && ./cpp26_bindings
g++-16 -std=c++2c -Wall -Wextra cpp26_bindings.cpp -o cpp26_bindings-gcc && ./cpp26_bindings-gcc
""")

Output

$ clang++ -std=c++2c -Wall -Wextra cpp26_bindings.cpp -o cpp26_bindings && ./cpp26_bindings
physics 78
total of a struct 254, of a tuple 10
elements after the first: 2
$ g++-16 -std=c++2c -Wall -Wextra cpp26_bindings.cpp -o cpp26_bindings-gcc && ./cpp26_bindings-gcc
physics 78
total of a struct 254, of a tuple 10
elements after the first: 2

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 cpp26_bindings_session.py

total adds up the members of any struct, tuple or array without knowing how many there are. Before C++26 that took std::apply and a lambda for tuples, and for structs a library or a separate version for each number of members. An earlier revision of the paper also allowed packs outside templates; the final one does not, and both compilers reject auto [first, ...rest] in an ordinary function.

Walk through the editions to see what each one changed about unpacking:

Timeline · 4 events in order How C++ learned to unpack a group of values Walk through the editions in order and watch the same unpacking get shorter, then learn to skip elements and to count them.
  1. Before C++17

    std::tie and std::ignore

    To unpack a returned tuple you declared the variables first, then assigned to std::tie(name, roll, std::ignore). The variables had to exist beforehand, so none of them could be const.

  2. C++17

    Structured bindings new syntax

    Paper P0217R3: auto [name, marks] = s; declares names for the elements of an array, a tuple-like type or a class whose data members are all public, one name per element.

  3. C++26, P2169R4

    The placeholder _ new syntax

    _ names an element you do not need and may appear several times in one declaration: auto [_, physics, _] = s; printed physics 78. GCC 14 and Clang 18 were the first versions to accept it.

  4. C++26, P1061R10

    Binding packs new syntax

    auto [first, ...rest] = value; gives one pack of names to the remaining elements, inside templates only. total(s) printed 254, and count_after_first(s) printed 2. GCC 16 and Clang 21 were the first versions with it.

The timeline has 4 events, from Before C++17 to C++26, P1061R10.

Each step took away something you used to write by hand: the declarations before std::tie, then a distinct name for every unwanted element, then a fixed count of names.

Checkpoint

Check: C++26 placeholders and binding packs

  1. Question 1 of 2 Which declaration is valid C++26 but not valid C++23?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: auto [_, physics, _] = s;

    C++26 lets _ appear several times, for the elements you do not need. Packs, the other C++26 addition, are limited to templates.

  2. Question 2 of 2 With the count_after_first template of cpp26_bindings.cpp, which unpacks const auto& [first, ...rest] = value; and returns sizeof...(rest), what does count_after_first(std::tuple{1, 2, 3, 4}) return?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 3 elements

    first takes the 1, and the pack rest takes the three elements after it, so sizeof...(rest) is 3. For the struct Scores, with three members, the program printed 2.

Practise: one summary, two shapes

summary.h declares two functions that compute the smallest value, the largest and the mean of a list of integers. summarise returns the struct Summary; summarise_tuple returns the same results as a std::tuple<int, int, double>. Write both. You may assume the list is never empty.

The starter code and its sample tests

C header · summary.h

// Starter code for the practice exercise: write summarise and summarise_tuple.
#pragma once
#include <tuple>
#include <vector>

struct Summary {
    int min = 0;
    int max = 0;
    double mean = 0.0;
    bool operator==(const Summary&) const = default;
};

// The smallest value, the largest and their mean. values is never empty.
inline Summary summarise(const std::vector<int>& values) {
    // TODO
    (void)values;
    return {};
}

// The same three results as a tuple, in the same order.
inline std::tuple<int, int, double> summarise_tuple(const std::vector<int>& values) {
    // TODO: a structured binding on summarise(values) makes this short
    (void)values;
    return {};
}

C++ · summary_tests.cpp

// Sample tests for summary.h. Build: clang++ -std=c++23 -Wall -Wextra summary_tests.cpp -o summary_tests
#include <print>
#include <tuple>
#include <vector>
#include "summary.h"

int checks = 0;
int failures = 0;

void check(bool ok, const char* what) {
    ++checks;
    if (!ok) {
        ++failures;
        std::println("FAIL {}", what);
    }
}

int main() {
    std::vector<int> marks{72, 91, 64, 85};
    check(summarise(marks) == Summary{.min = 64, .max = 91, .mean = 78.0}, "min, max and mean of 72, 91, 64, 85");
    check(summarise({-5}) == Summary{.min = -5, .max = -5, .mean = -5.0}, "one value is the min, the max and the mean");
    check(summarise({1, 2}).mean == 1.5, "the mean keeps its fraction");

    auto [low, high, mean] = summarise_tuple(marks);
    check(low == 64 && high == 91 && mean == 78.0, "the tuple holds min, max and mean, in that order");
    check(summarise_tuple({7}) == std::tuple{7, 7, 7.0}, "the tuple of one value");

    std::println("{} of {} checks passed", checks - failures, checks);
    return failures == 0 ? 0 : 1;
}
The sample tests against the starter code Python · summary_session.py
from session import run

# The sample tests run against the starter code, before any TODO is done.
run("""
clang++ -std=c++23 -Wall -Wextra summary_tests.cpp -o summary_tests && ./summary_tests
g++-16 -std=c++23 -Wall -Wextra summary_tests.cpp -o summary_tests-gcc && ./summary_tests-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra summary_tests.cpp -o summary_tests && ./summary_tests
FAIL min, max and mean of 72, 91, 64, 85
FAIL one value is the min, the max and the mean
FAIL the mean keeps its fraction
FAIL the tuple holds min, max and mean, in that order
FAIL the tuple of one value
0 of 5 checks passed
[exit status 1]
$ g++-16 -std=c++23 -Wall -Wextra summary_tests.cpp -o summary_tests-gcc && ./summary_tests-gcc
FAIL min, max and mean of 72, 91, 64, 85
FAIL one value is the min, the max and the mean
FAIL the mean keeps its fraction
FAIL the tuple holds min, max and mean, in that order
FAIL the tuple of one value
0 of 5 checks passed
[exit status 1]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 summary_session.py

When both functions are right, the tests print 5 of 5 checks passed and the program exits with status 0. Two hints: std::ranges::minmax(values) returns the smallest and the largest value in one pass, as a struct you can unpack with a structured binding, and summarise_tuple can unpack summarise(values) the same way and return a tuple of the three names. Then compare the call sites in the tests: summarise(marks).mean names what it reads, while the tuple needs the reader to remember which position holds the mean.

When the five checks pass, work through the practice session on pairs, tuples, bindings, map loops, sorting keys, the choice of a grouping and the C++26 additions. It starts where your answers so far were weakest and explains each choice once you check it:

Practice that adapts to you

Practise this lesson

20 questions about 7 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 20 What type does std::pair best{"Asha", 91}; have?

    Choose one answer.

    Show the answer: Question 1 of 20

    Answer: std::pair<const char*, int>

    The compiler deduces the types from the values, and a string literal decays to const char*. Write std::pair<std::string, int>, or use "Asha"s from std::string_literals, to get a std::string.

  2. Question 2 of 20 auto range = std::minmax({72, 91, 85, 64}); What are range.first and range.second?

    Choose one answer.

    Show the answer: Question 2 of 20

    Answer: 64 and 91

    The standard library returns a pair wherever one call has two results: minmax returns the smallest and the largest value, and map's insert returns where the element is and whether it was inserted.

  3. Question 3 of 20 For std::pair<int, std::string> values, which comparison is true?

    Choose one answer.

    Show the answer: Question 3 of 20

    Answer: std::pair{2, std::string{"b"}} < std::pair{3, std::string{"a"}}

    Pairs compare like words in a dictionary: first decides, and second only when the firsts are equal. Writing std::string{…} matters: with bare literals the pair would hold pointers and compare addresses.

  4. Question 4 of 20 What does std::tuple_size_v<std::tuple<std::string, int, double>> give, and when is it known?

    Choose one answer.

    Show the answer: Question 4 of 20

    Answer: 3, while compiling

    A tuple's element types, and therefore their number, are fixed by its type. That is also why a structured binding can unpack a tuple: the compiler knows how many names it needs.

  5. Question 5 of 20 Given std::tuple<int, std::string, int> t;, which call does not compile?

    Choose one answer.

    Show the answer: Question 5 of 20

    Answer: std::get<int>(t)

    Reading a tuple element by its type works only when that type occurs exactly once. int occurs twice here, so the call is ambiguous and is rejected at compile time; the positions 0 and 2 always work.

  6. Question 6 of 20 Why must name and roll be declared before std::tie(name, roll, std::ignore) = topper();, when auto [name, roll, marks] = topper(); declares them itself?

    Choose one answer.

    Show the answer: Question 6 of 20

    Answer: std::tie makes references to variables that already exist and assigns to them; a structured binding declares the names

    Before C++17, std::tie was the usual way to unpack a returned tuple into variables declared beforehand. A structured binding declares the names in the same statement, and they can be const auto& as well.

  7. Question 7 of 20 What does auto [name, marks] = s; declare?

    Choose one answer.

    Show the answer: Question 7 of 20

    Answer: One unnamed copy of s, and two names for its members

    A structured binding always creates one unnamed variable from its initialiser. auto makes it a copy, auto& a reference, and the names refer to its members.

  8. Question 8 of 20 Which of these can a structured binding unpack in ordinary code outside the class?

    Choose every answer that is right.

    Show the answer: Question 8 of 20

    Answer:

    • struct Point { int x; int y; };
    • std::pair<std::string, int>
    • int sides[3]

    Arrays, tuple-like types and classes whose data members are all public can be unpacked. A vector's size is known only at run time, and private members cannot be bound outside the class's own members.

  9. Question 9 of 20 A function takes const Student& s and writes auto& [name, marks] = s;. What can it do with marks?

    Choose one answer.

    Show the answer: Question 9 of 20

    Answer: Read it, but not assign to it

    The unnamed variable of auto& has the type of the initialiser, const Student here, so its members are const. Both compilers reject an assignment through marks.

  10. Question 10 of 20 Which loop over a std::map<std::string, Marks> m reads every element without copying it?

    Choose one answer.

    Show the answer: Question 10 of 20

    Answer: for (const auto& [name, marks] : m)

    The map's elements are std::pair<const std::string, Marks>. A reference to a pair with a non-const key does not match that type, so the compiler copies each element into a temporary, and both other loops copy by value.

  11. Question 11 of 20 A std::map<std::string, Order> has 1,000 elements. How many of them does for (auto [id, order] : orders) copy?

    Type a number.

    Show the answer: Question 11 of 20

    Answer: 1000 elements

    A plain auto copies each element into the unnamed variable before the names refer to it. Write const auto& [id, order] to read the elements where they are.

  12. Question 12 of 20 You want to add 5 to every value of std::map<std::string, int> marks. Which loop does it?

    Choose one answer.

    Show the answer: Question 12 of 20

    Answer: for (auto& [name, value] : marks) value += 5;

    To change values in place, bind with auto&: the key stays const, the value can change. To read, use const auto&. Plain auto is for when you really want a copy.

  13. Question 13 of 20 Tuples compare lexicographically. Why is std::tuple{3, 1} < std::tuple{3, 0} false?

    Choose one answer.

    Show the answer: Question 13 of 20

    Answer: The first elements tie, so the second ones decide, and 1 is not less than 0

    Lexicographic comparison works like a dictionary: the first elements decide, then the second ones only on a tie, and so on. (3, 1) and (3, 0) tie on 3, and 1 > 0.

  14. Question 14 of 20 Which comparison sorts students by marks from high to low, and by name from A to Z when the marks are equal?

    Choose one answer.

    Show the answer: Question 14 of 20

    Answer: std::tie(b.marks, a.name) < std::tie(a.marks, b.name)

    Putting b's marks on the left reverses the first key, so higher marks come first; keeping a's name on the left keeps the names in ascending order. The second choice sorts both keys ascending, the third both descending.

  15. Question 15 of 20 To sort struct Result { std::string name; int theory; int practical; }; by the total of theory and practical, why does std::tie(b.theory + b.practical, a.name) not compile?

    Choose one answer.

    Show the answer: Question 15 of 20

    Answer: std::tie makes references to named variables or members, and a sum is a temporary value it cannot refer to

    std::tie builds references, so every argument must be an existing object. For a computed key, compare tuples of values, or compute the totals once before sorting.

  16. Question 16 of 20 Rule F.21 of the C++ Core Guidelines is about functions that return several values. What does it prefer?

    Choose one answer.

    Show the answer: Question 16 of 20

    Answer: Returning a struct

    F.21: to return multiple out values, prefer returning a struct. Summary with min, max and mean is clearer than std::tuple<int, int, double>, whose two ints are easy to swap.

  17. Question 17 of 20 A std::map<std::string, int> hands out its elements as std::pair<const std::string, int>. Why is a pair a good fit there, when a named struct is better for a function's results?

    Choose one answer.

    Show the answer: Question 17 of 20

    Answer: A key with its value is obvious on the spot, and a generic container cannot know what your values mean

    Keep pairs and tuples for code that does not know what its values mean, such as containers and templates, and for results whose meaning is obvious where they are used.

  18. Question 18 of 20 In C++26, what does _ mean in auto [_, physics, _] = s;?

    Choose one answer.

    Show the answer: Question 18 of 20

    Answer: It names an element you do not need, and it may appear more than once in one declaration

    The placeholder _ marks elements you will not use. Before C++26, each of them needed a distinct name, such as unused1 and unused2.

  19. Question 19 of 20 Where may auto [first, ...rest] = value; appear under the final C++26 rules?

    Choose one answer.

    Show the answer: Question 19 of 20

    Answer: Only inside a template, such as a function template

    A pack is used like any other pack, with sizeof... or a fold expression, and packs exist only in templates. That is why total and count_after_first in cpp26_bindings.cpp are templates.

  20. Question 20 of 20 With template <class T> int total(const T& value) { const auto& [...parts] = value; return (0 + ... + parts); }, what does total(std::array{1, 2, 3, 4, 5}) return?

    Type a number.

    A hint

    std::array is a tuple-like type, so the pack gets one name per element.

    Show the answer: Question 20 of 20

    Answer: 15

    parts gets the five elements of the array, and the fold expression adds them to 0: 1 + 2 + 3 + 4 + 5 = 15. The same template gave 254 for the struct Scores and 10 for a tuple of 1 to 4.

Interview questions

Fresher · What does auto [a, b] = p; declare, and how is it different from auto& [a, b] = p;?

It declares one unnamed variable and two names. auto [a, b] = p; copies p into the unnamed variable, and a and b refer to the elements of that copy, so changing them leaves p as it was. With auto&, the unnamed variable is a reference to p, so a and b refer to the elements of p itself and assigning to them changes p. const auto& gives read-only access without a copy, which is the usual choice in loops such as for (const auto& [key, value] : m). The number of names must equal the number of elements, and the object must be an array, a tuple-like type such as std::pair or std::tuple, or a class whose non-static data members are all public. A good answer also mentions that a plain auto copies every element of a container it loops over.

Two follow-ups often come next: why a reference to the wrong pair type still copies, and whether private members can be unpacked. Settle each one before you look at its explanation:

Checkpoint

Interview round: two follow-up questions

  1. Question 1 of 2 Follow-up: "The loop says const std::pair<std::string, Marks>&, a reference. Why does it still copy every element?"

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The map's elements are pair<const std::string, Marks>, another type, so the reference binds to a temporary pair built from each element

    Always let the compiler name the element type: const auto& [key, value] binds to std::pair<const Key, T> exactly, and a hand-written type that differs in one const turns every pass into a copy.

  2. Question 2 of 2 Follow-up: "Can a structured binding unpack a class whose data members are private?"

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Not from outside the class, unless the class describes its elements through tuple_size, tuple_element and get

    A structured binding unpacks arrays, tuple-like types and classes whose data members are accessible where the binding is written. A class can opt in from outside by providing the tuple-like protocol.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    You count trips per city and day with std::unordered_map<std::pair<std::string, int>, int>, and the code does not compile, while the same std::map works. Why, and what are your options? Compare them.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    A widely used function returns std::tuple<int, int, double, bool>, and callers keep mixing up the two ints. How do you move it to a named struct without breaking every caller at once, and what still breaks?

    Model answer, Pro. First step and follow-ups

Key takeaways

  • std::pair has first and second; std::tuple has any fixed number of elements, read with std::get<i>. A string literal in a deduced pair is a const char*, not a std::string.
  • auto [x, y] = e; declares an unnamed copy of e and names for its elements; auto& and const auto& bind to e itself.
  • Structured bindings unpack arrays, tuple-like types and classes with only public data members, with exactly one name per element.
  • Loop over a map with const auto& [key, value]. A plain auto, or a reference to the wrong pair type, copies every element, and -Wall warns about the second.
  • Tuples compare element by element, so std::tie(b.marks, a.name) < std::tie(a.marks, b.name) sorts by marks from high to low and then by name.
  • Prefer a named struct for results that mean something; C++26 adds _ for unwanted elements and binding packs in templates.

Terms in this lesson

lexicographic comparison
Comparing two sequences element by element from the first: the first pair of elements that differ decides, and a sequence that runs out first is the smaller. Tuples, pairs, std::array and strings compare this way, like words in a dictionary.
structured binding
A declaration such as auto [name, marks] = s; (C++17) that gives one name to each element of an array, a tuple-like type or a class whose data members are all public. The names refer to the members of one unnamed variable made from the initialiser: a copy with auto, s itself with auto&.
tuple-like type
A type that describes its elements through std::tuple_size, std::tuple_element and get, as std::pair, std::tuple and std::array do. Structured bindings unpack such a type by position, whatever its members are called.

Corrections

  • The C++26 section now says that C++26 adds several features to structured bindings, of which it shows two, and std::tie is said to assign each element, not to copy it.

References

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.