C++ struct Structured Bindings

Introduction

Structured binding binds the variable names to elements of compile-time known expressions, such as arrays or maps.

If we want to have multiple variables taking values of expression elements, we use the structured bindings.

The syntax is:

auto [myvar1, myvar2, myvar3] = some_expression; 

A simple example where we bound three variables to be aliases for three array elements would be:

int main() 
{ 
    int arr[] = { 1, 2, 3 }; 
    auto [myvar1, myvar2, myvar3] = arr; 
} 

Now we have defined three integer variables.

These variables have array elements values of 1, 2, 3, respectively.

These variables are copies of array elements.

Making changes to variables does not affect the array elements themselves:

#include <iostream> 

int main() /*from   ww w  .  java 2s .  c om*/
{ 
    int arr[] = { 1, 2, 3 }; 
    auto [myvar1, myvar2, myvar3] = arr; 
    myvar1 = 10; 
    myvar2 = 20; 
    myvar3 = 30; 
    for (auto el : arr) 
    { 
        std::cout << el << ' '; 
    } 
} 

We can make structured bindings of reference type by using the auto& syntax.

This means the variables are now references to array elements and making changes to variables also changes the array elements:

#include <iostream> 

int main() /*from   ww w  .j a v  a  2 s. c  om*/
{ 
    int arr[] = { 1, 2, 3 }; 
    auto& [myvar1, myvar2, myvar3] = arr; 
    myvar1 = 10; 
    myvar2 = 20; 
    myvar3 = 30; 
    for (auto el : arr) 
    { 
        std::cout << el << ' '; 
    } 
} 

It is an excellent way of introducing and binding multiple variables to some container-like expression elements.




PreviousNext

Related