C++ Structured Bindings
In this page:
What is Structured Binding?
Structured bindings, introduced in C++17, let you unpack multiple values from a struct, pair, tuple, or array into individually named variables in a single declaration, instead of accessing each member one at a time through dot or index syntax.
Example: What is Structured Binding?
#include <iostream>
#include <utility>
int main() {
std::pair<int, int> point(3, 4);
auto [x, y] = point;
std::cout << x << "," << y << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Binding to Struct Members
For a struct, the syntax auto [a, b] = myStruct; unpacks its public members in declaration order into the variables a and b. The number of names inside the brackets must exactly match the number of members being unpacked, or the compiler rejects it.
Example: Binding to Struct Members
#include <iostream>
struct Point { int x; int y; };
int main() {
Point p{3, 4};
auto [a, b] = p;
std::cout << a << "," << b << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Binding to Arrays
The same bracket syntax works on a fixed-size C-style array -- auto [x, y, z] = myArray; unpacks each of its three elements into separate variables, which is often more readable than repeatedly indexing the array by number.
Example: Binding to Arrays
#include <iostream>
int main() {
int arr[3] = {1, 2, 3};
auto [x, y, z] = arr;
std::cout << x << " " << y << " " << z << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using References in Bindings
By default, structured bindings copy each unpacked value into its new variable, so changes to the bound variable don't affect the original struct or array. Declaring the binding as a reference -- auto& [a, b] = myStruct; -- instead binds directly to the original members, so modifications propagate back.
Example: Using References in Bindings
#include <iostream>
struct Point { int x; int y; };
int main() {
Point p{1, 2};
auto &[x, y] = p;
x = 100;
std::cout << p.x << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using const References
When you want to unpack values without copying but also want to guarantee they can't be accidentally modified, const auto& [a, b] = myStruct; gives you a read-only reference binding -- the best choice when you're only inspecting a large struct's fields.
Example: Using const References
#include <iostream>
struct Point { int x; int y; };
int main() {
Point p{5, 6};
const auto &[x, y] = p;
std::cout << x << " " << y << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: