C++ structured bindings
Structured bindings give names to the individual parts of an array, tuple-like object, or simple structure. They were introduced in C++17.
Simple example
auto [x, y] creates two names from the two elements of position. Compile it as C++17 or newer:
Supported types
Structures
The names follow member declaration order, not their names. The number of bindings must match the number of decomposed members.
Arrays
Pairs and tuples
std::pair, std::tuple, and other tuple-like types can be decomposed when their element count and access operations are defined.
Copies, references, and const
Choose the qualifier according to whether you need a copy or access to the original object:
| Binding | Behavior |
|---|---|
auto [x, y] = value; |
Work with a copy. |
auto& [x, y] = value; |
Modify the original elements. |
const auto& [x, y] = value; |
Read the original elements without copying. |
auto&& [x, y] = expression; |
Preserve whether the expression is an lvalue or rvalue. |
Use const auto& in read-only loops
It avoids copying each element while preventing accidental modification.
Structured bindings in loops
They make key-value iteration easier to read:
For a map element, the first binding is the key and the second is the mapped value.
Returning multiple values
A function can return a small structure or tuple and let the caller name each result:
Prefer a named structure when the fields have domain meaning. A pair or tuple is suitable for a small, obvious local result.
Use in an if statement
A structured binding can appear in an if initializer. This is common with container insertion:
Both names exist only inside the if and else statements.
Common mistakes
- Using the wrong number of names causes a compile error.
- Omitting
&creates a copy, so changes do not affect the original object. - Binding names are chosen by position; renaming structure members does not rename the bindings.
- Large values can be expensive to copy. Prefer
const auto&when only reading them. _is an ordinary variable name in C++; it does not discard an unwanted element.