cpp17 · medium
C++17: Structured Bindings
Structured bindings (C++17) decompose a std::pair, std::tuple, fixed array, or public-member aggregate into named variables in a single declaration, e.g. auto [name, age] = *map.begin(). The names are aliases for the members of an unnamed compound object rather than independent variables, so cv-qualifiers and references go on the auto — const auto& [k, v] binds the whole thing const and by reference, avoiding a copy of each element during iteration. The canonical example is auto [it, ok] = m.insert(...), which makes multi-value returns readable at the call site. Limits: the element count must be known at compile time and match the number of names, and (before C++20) a binding cannot be captured in a lambda.
C++17 structured bindings: auto [a,b] = expr decomposes a pair/tuple/array/struct into named aliases of one hidden object — use const auto&/auto& to control const-ness and avoid copies; replaces .first/.second and std::tie.
The code
std::map<std::string, int> ages{{"ana", 30}, {"bob", 25}};
// pre-C++17: pair.first / pair.second, or std::tiefor (const auto& kv : ages) use(kv.first, kv.second);
// C++17: name the parts directlyfor (const auto& [name, age] : ages) // bind both fields use(name, age);
auto [it, ok] = ages.insert({"cara", 41}); // pair -> two namesif (!ok) /* key already present */ ;What this lesson walks through
- 01Name the parts directly
- 02It binds — it is not a new object
- 03Gotcha — auto [..] COPIES by default
- 04Interview angle
A map element is a pair. Structured bindings give its members names by POSITION: auto [name, age] binds the first field to name and the second to age — no more .first / .second.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of C++17: Structured Bindings and 100+ animated C++ interview lessons.