×

Structured Binding in C++

Structured binding is the new feature of C++ 17. It is used to bind the specified name with an element of the initializer. Structure binding is used to declare multiple variables from the struct. The primary purpose of structure binding is to make the code clean and easy to understand. The structured binding does not support reference type. 

Syntax:

auto ref-operator(optional)[identifier-list] = expression;


// Or


auto ref-operator(optional)[identifier-list]{expression};


// Or


auto ref-operator(optional)[identifier-list](expression);

Parameter for structured binding:

  • There is an auto parameter.
  • The ref operator is used for either & or &&.
  • The identifier list is used to list the comma variable.
  • The expression does not have a comma operator and has the class type of array or non-union class.

Basic Type Deduction

It is either a type of std::tuple or a type of non-static data member. Non-static data member has accessible by others and is declared by some other class variable. In a Structured binding declaration, binding is possible in three different ways. 

  • Case-1: If we have an array type E, the name is bound with the array elements.
  • Case-2: If we have a non-union class E and tuple_size is a complete type, then tuple_like protocol is implemented.
  • Case-3: If we have a non-union class E and tuple_size is not a complete type, then the named bind with the public data member. 

Example 1:

#include <bits/stdc++.h>
using namespace std;


struct Point {
 int a;
 int b;
};
 
int main()
{
 Point p = {5, 8};
 
 int a_coord = p.a;
 int b_coord = p.b;
 
 cout <<"The Coordinate of A is: "<< a_coord << endl;
 cout <<"The Coordinate of B is: "<< b_coord << endl;
 
 return 0;
}

Output:

The Coordinate of A is: 5
The Coordinate of B is: 8

Example 3:

This code runs on the C++17 version.

#include <bits/stdc++.h>
using namespace std;


struct Point
{
 int a;
 int b;
};
int main( )
{
 Point k = { 5,8 };
 auto[ a_coord, b_coord ] = k;
 
 cout <<"The co-ordinate of A: "<< a_coord << endl;
 cout <<"The co-ordinate of B: "<< b_coord << endl;
 
 return 0;
}


Output:

The co-ordinate of A: 5
The co-ordinate of B: 8

Application of Structured Binding

With the help of structured binding, we can fetch the elements from an array. In this example, we are going to take E as an array. So with the help of structured binding, the name is associated with array E. Let's understand this with an example.

Example 4:

#include <bits/stdc++.h>
using namespace std;


int main()
{


 int arr[3] = { 5 , 6 , 8 };
 auto[a , b , c] = arr;
 
 cout << a <<""<< b <<""<< c << endl;


 return 0;
}

Output:

5 6 8

It should be noted that the number of elements in the list and elements in the array must be equal. If these two are not equal, the compiler throws the error. 

Example 5:

#include <bits/stdc++.h>
#include <map>
using namespace std;


int main()
{
 map<string, string> sites;
 
 sites.insert({ "javaTpoint", "is a website for coding resource" });
 sites.insert({ "tutorial and example", "is a website for coding resource" });
 sites.insert({ "Wikipedia", "Resources + References" });


 for (auto & [ key, value ] : sites)
 {
 cout << key.c_str() <<""<< value.c_str() << endl;
 }
 
 return 0;
}

Output:

Wikipedia Resources + References
javaTpoint is a website for coding resource
tutorial and example is a website for coding resource

Variables such as volatile and const are both used to declare the qualifier. This qualifier makes the type of declaration variable.


Related Topics

C++ Signal Handling

Signals are interruptions sent by the operating system to a process to cause it to cease doing its current job and focus on the task for which the interrupt was...

4 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.

C++ Inline function

A C++ function that extends in line when called is known as an inline function. It reduces function call overhead by having the compiler use the function code rather than...

4 minutes read.

Palindrome using Do-while loop in C++

What is Palindrome? A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++...

5 minutes read.

Use of Inheritance in C++

What is inheritance in c++? Inheritance is fundamental in object-oriented programming (OOP) languages like C++. It allows a programmer to create a new class (called a derived class) that inherits the...

4 minutes read.

Armstrong Number using While Loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

4 minutes read.

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we...

3 minutes read.

Armstrong number using for loop in C++

What is For Loop? A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax that can be...

4 minutes read.

Backtracking Time Complexity in C++

Introduction to Backtracking Backtracking is an important part of programming languages, and with the help of backtracking, we can do many operations in an advanced data structure. For doing major operations,...

4 minutes read.

Observer Design Pattern in C++

The Observer design pattern is a behavioural design pattern that allows an object (known as the subject) to notify other objects (known as observers) when its state changes. This is...

3 minutes read.

Types of polymorphism in C++

What is polymorphism in C++ ? Polymorphism literally translates to "multiple forms". This indicates that the same thing behaves differently depending on the context in programming. Polymorphism is a feature of C++...

6 minutes read.

Hospital Management Project in C++

The following capabilities are required to build a hospital management project: These are as follows: hospitals' names, contact information, and lists of doctors and patients. Activities Supported Hospital Data Print Patients' data to...

4 minutes read.

How to Reverse a String in C++ using For Loop

For Loop: We may loop through a certain section of C++ code repeatedly using the for loop. A for loop is carried out if the test expression yields a true result. The...

4 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left,...

4 minutes read.

CPP Templates

C++ provides a powerful feature called template, which allows the definition of generic classes and generic functions. Generic programming is a technique where different algorithms work in communion by using...

4 minutes read.

Array of Vectors in C++ STL

Prerequisites: C++ STL Arrays and C++ STL Vector. A group of items kept in consecutive memory region is known as an array. It is to group similar objects of the same...

4 minutes read.

C++ Try-Catch

Every useful program will eventually encounter unexpected outcomes. By entering data that are incorrect, users might create mistakes. Sometimes the program's creator didn't consider all of the options or was...

7 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

Pure Virtual Function in C++ With Example Program

What is a Virtual Function? A virtual function is created inside a class with the keyword virtual. A virtual function does not have any value to be returned. Once a virtual...

3 minutes read.