Structured bindings, introduced in C++17, provide a concise and intuitive way to unpack multiple values from tuples, arrays, and structures. This feature enhances code readability and reduces the verbosity often associated with accessing individual elements of compound objects.
auto
for automatic type deduction or with explicit types#include <iostream>
#include <tuple>
int main() {
std::tuple<int, double, std::string> person(30, 1.75, "John Doe");
auto [age, height, name] = person;
std::cout << "Name: " << name << ", Age: " << age << ", Height: " << height << " m" << std::endl;
return 0;
}
person
containing an integer, a double, and a stringage
, height
, and name
auto
#include <iostream>
struct Point {
double x;
double y;
};
Point getPoint() {
return {3.14, 2.71};
}
int main() {
auto [x, y] = getPoint();
std::cout << "X: " << x << ", Y: " << y << std::endl;
return 0;
}
Point
structure with public data members x
and y
getPoint()
function returns a Point
objectPoint
into x
and y
variables#include <iostream>
#include <array>
int main() {
std::array<int, 3> coordinates = {1, 2, 3};
auto [x, y, z] = coordinates;
std::cout << "X: " << x << ", Y: " << y << ", Z: " << z << std::endl;
return 0;
}
std::array
of integers representing 3D coordinatesx
, y
, and z
std::array
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> ages = {{"Alice", 30}, {"Bob", 25}, {"Charlie", 35}};
for (const auto& [name, age] : ages) {
std::cout << name << " is " << age << " years old." << std::endl;
}
return 0;
}
std::map
const auto&
ensures we're using references and not copying the dataname
and age
variablesstd::pair
or iterator->first
and iterator->second
static
, thread_local
, and extern
storage class specifiersauto
, the binding follows reference collapsing rules similar to template argument deductionStructured bindings in C++ provide a powerful and expressive way to work with compound objects such as tuples, arrays, and structures. They enhance code readability, reduce verbosity, and make it easier to work with multiple return values or complex data structures. By allowing simultaneous declaration and initialization of multiple variables, structured bindings streamline the process of unpacking data, leading to more intuitive and maintainable code. Whether working with standard library containers, custom structures, or multi-value returns, structured bindings offer a clean and efficient syntax for modern C++ programming.
Previous Page | Course Schedule | Course Content