basic introduction
-
Basic syntax
The syntax for structured binding is:auto [var1, var2, ...] = expr;
expr
is an expression that returns a class or structurevar1
,var2
is the variable name of the receiving field- The number and order of variables must
expr
be consistent with the fields
-
Automatic type derivation
: Structured binding willexpr
automatically deduce the corresponding type for each var based on the field type. -
Nested structure support
Ifexpr
the field is also a structure containing multiple fields, it can be further nested and destructured:struct Inner { int a, b; }; struct Outer { int c; Inner inner; }; Outer ret...; auto [c, [a, b]] = ret; // 嵌套解构 Inner
-
Omitting variable names
can be used to_
omit unnecessary variables:auto [a, _, c] = expr; // 忽略第二个字段
-
In conjunction with other syntaxes,
structured binding can be coupled withif/switch/for
statements such as:if(auto [x, y] = getPoint(); x > 0 && y > 0) { // 使用x,y } for(auto [k, v] : map) { // 使用k,v }
-
Returning a reference
If aexpr
reference is returned, the destructured fields will also be references. -
Purpose
Structured binding is very suitable for destructuring a structure after returning it from a function, which can simplify the code and avoid creating temporary variables.
Examples of usage of different data types
Tuples
#include <tuple>
std::tuple<int, double, std::string> getTuple() {
return std::make_tuple(42, 3.14, "Hello");
}
int main() {
auto [intValue, doubleValue, stringValue] = getTuple();
// Now you can use intValue, doubleValue, and stringValue as separate variables.
return 0;
}
Arrays
int main() {
int arr[] = {
1, 2, 3, 4, 5};
auto [a, b, c, d, e] = arr;
// Now you can use a, b, c, d, and e as separate variables containing the elements of the array.
return 0;
}
Pair
#include <utility>
std::pair<int, double> getPair() {
return std::make_pair(42, 3.14);
}
int main() {
auto [key, value] = getPair();
// Now you can use key and value as separate variables.
return 0;
}
pass by reference
int main() {
int x = 42, y = 23;
auto& [rx, ry] = std::tie(x, y);
// Now rx and ry are references to x and y, respectively.
rx = 100;
// This will modify the original value of x to 100.
return 0;
}
element ignored
std::tuple<int, double, std::string> getTuple() {
return std::make_tuple(42, 3.14, "Hello");
}
int main() {
auto [intValue, _, stringValue] = getTuple();
// Here, we're ignoring the second element (doubleValue) of the tuple.
return 0;
}