Structured bindings
- C++ course
- Advanced
- Lesson 2/83
- 5 min
Learn multi-variable assignment with structured bindings.
Structured bindings
Structured bindings (C++17) bind the members of a struct, pair or tuple to separate variables in one line. The syntax is auto [a, b] = p;. Here a and b become local names for p.first and p.second.
This is more readable than p.first and p.second. When a function returns multiple values via std::pair or std::tuple, the caller unpacks the result easily with a binding.
Multiple returns with std::pair
A function returns two values with std::pair<T1, T2>. The caller unpacks with auto [a, b] = func();. Example: std::pair<bool, int> find(int x) returns whether it found and the value.
Structured bindings are cleaner than std::get<0> and std::get<1>. The compiler creates one variable per member with no run-time cost. The same syntax works for std::array and plain structs.
Practice Bind the min_max function
Write std::pair<int, int> min_max(int a, int b): put the smaller value in first, the larger in second. In main, bind the result with auto [mn, mx] = min_max(7, 3); and print mn via std::cout.
Starter code
#include <iostream>
#include <utility>
// Write the min_max function
int main() {
// Bind and print the result
return 0;
}Sample solution
#include <iostream>
#include <utility>
std::pair<int, int> min_max(int a, int b) {
return {std::min(a, b), std::max(a, b)};
}
int main() {
auto [mn, mx] = min_max(7, 3);
std::cout << mn;
return 0;
}Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the binding syntax
auto ____ = make_pair(3, 7);
auto [a, b] = make_pair(3, 7);
Explanation: Square brackets are used for structured bindings.
2 Which line is a valid structured binding?
- auto (a, b) = p;
- auto [a, b] = p; Correct answer
- auto {a, b} = p;
- auto <a, b> = p;
Explanation: Square brackets are used for structured bindings.
3 Match the syntax to its purpose
| Term | Meaning |
|---|---|
auto [a, b] = p |
Bind pair members |
auto [a, b, c] = t |
Bind tuple members |
auto& [a, b] = p |
Bind by reference |
auto [a, b]{a, b} |
Not a template |