c++ – New syntax for declaring variables from a composite object


In c ++ 17, there is a new syntax for declaring variables of the form:

auto [x, y, z] = f();

where f() is a function that returns a composite object (array, tuple, structure, etc.).

What is the name of this syntax and what does it do?


This construct is called Structured binding declaration (It can be translated as "structured binding declaration") and allows you to declare a group of variables at once (possibly even of different types) if there is an initializing expression. The example uses the f function as this expression.

Let's look at a few examples of use:

#include <iostream>
#include <string>
#include <tuple>
#include <map>

struct S {
    int i;
    std::string s;
    double d;

S f() { return { 42, "hello", 1.5 }; }

std::map<int, std::string> g() { return { { 1, "one" }, { 2, "two" }, { 3, "three" } }; }

int main() {

    auto [i, s, d] = f();
    std::cout << i << s << d << "\n";

    int a[] = { 5, 6, 7 };
    auto& [x, y, z] = a;
    std::cout << x << y << z << "\n";
    x--; y++; z*=2;
    std::cout << a[0] << a[1] << a[2] << "\n";

    auto [ss, dd, ii] = std::make_tuple("ololo", 0.5, 100500);
    std::cout << ss << dd << ii << "\n";

    for (auto [k, v] : g()) {
        std::cout << "key=" << k << " value=" << v << "\n";

Execution result:

key=1 value=one
key=2 value=two
key=3 value=three

You can see that the variables i , s , d initialized with the values ​​of the corresponding members of the structure S It is worth noting here that it is not the coincidence of names that is important, but the order of the members.

When binding variables x , y , z with elements of array a , reference & was used. That. the subsequent change of variables affects the state of the array elements.

The variables ss , dd , ii initialized with the elements of the tuple. Everything seems to be simple here.

Using in a range loop allows you to immediately split a composite element (in this case std::pair ) into components. A similar c ++ 11 style loop might look like this:

for (auto e: g())
    std::cout << "key=" << e.first << " value=" << e.second << "\n";

That. this construct makes it easier to write code when you need to access parts of a composite object.

Scroll to Top