liveBook · Manning

Structured binding

As explained in Learn C++ by Example

A structured binding is C++ declaration syntax that introduces names referring to elements of an aggregate, tuple-like object, or pair.

Structured binding is C++ declaration syntax for naming elements of pairs, tuples, arrays, and structures. Write auto followed by names in brackets, such as auto [x, y, z] = three_numbers;. section 7.1.2

Use structured bindings to make element access clearer:

  • Replace repeated std::get calls when unpacking a tuple. section 7.1.2
  • Name map entries directly in a range-based loop, often as const references to avoid copying strings. section 7.1.3
  • Choose value or reference bindings deliberately: auto [x, y, z] copies the hidden tuple or pair, while auto& [x, y, z] binds to the existing object. section 7.1.2

Iterating a dictionary

A map loop can expose each key and definition directly: for (const auto& [word, definition] : keywords) { ... }. The same pattern appears in an answer-smash game, where each keyword is paired with an overlapping dictionary word and its offset: auto [second_word, offset] = find_overlapping_word(word, dictionary);. section 7.1.3

Structured bindings also name tuple references produced by std::views::zip, letting a loop move corresponding items from two collections without joining or copying the collections. section 9.3.5

How Learn C++ by Example covers it

How deep it goes
Explains syntax, supported types, copying, references, and hidden-object mechanics without pursuing full language specification details.
Examples
Demonstrates tuple unpacking, dictionary iteration, answer-smash results, and zipped slot-machine reels.
What it assumes
Assumes familiarity with auto, references, pairs, tuples, maps, range-based loops, and std::get, while demonstrating their combination.
What you can do after
Apply it via C++17 syntax to name pair, tuple, array, structure, map, and zipped-view elements while controlling copies.
How it connects
Connects structured bindings with std::pair, std::tuple, std::map, range views, references, and structured return values.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.