🔑Go deeper — read the bookC++ Keywords by Version — Specifiers & Attributes— runnable code & full walkthrough →

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.

🔑 Key line

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::tie
for (const auto& kv : ages)
use(kv.first, kv.second);
// C++17: name the parts directly
for (const auto& [name, age] : ages) // bind both fields
use(name, age);
auto [it, ok] = ages.insert({"cara", 41}); // pair -> two names
if (!ok) /* key already present */
;

What this lesson walks through

  1. 01Name the parts directly
  2. 02It binds — it is not a new object
  3. 03Gotcha — auto [..] COPIES by default
  4. 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.

← Previous
C++17 Features — With Use Cases
Next →
C++17: if constexpr