×

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++ Program to find largest subarray with 0 sum

Write a program to find the largest subarray that has a sum zero. The array contains positive and negative numbers. Print the length of the max subarray whose sum turns...

4 minutes read.

Memset in C++

Memset () is a function in the C++ programming language that fills memory blocks. The value of "ch" is first converted to an unsigned character. In this case, "ch" denotes the...

3 minutes read.

C++ Structs

We frequently encounter scenarios in which we must store a bunch of data, whether of comparable or dissimilar data kinds. Arrays are used to hold a group of data of...

6 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.

Different Ways to Compare Strings in C++

This section will go over the many methods for comparing strings in the C++ programming language. The string comparison checks if the first string is equal to another string. HELLO...

6 minutes read.

Reverse an Array in C++

The many approaches to reverse an array in the C++ programming language will be discussed in this section. The term "reverse of an array" refers to changing the order of...

8 minutes read.

How to enter a name in C++

A name is a string or array of characters or letters. The string is one of the most helpful data types offered by the C++ library. A string helps the...

4 minutes read.

Input Iterators in C++

What are input iterators? Input iterators are used in sequence for carrying out input operations where each value is read-only. It is pointed by the iterator and further incremented. All the iterators...

4 minutes read.

Multilevel Inheritance

C++ Multilevel Inheritance Multilevel inheritance is such an inheritance in which a derived class is created from another derived class. C++ Multilevel Inheritance Example In this example, a base class Student is inherited in...

2 minutes read.

Factorial of a Number in C++ using while Loop

What is a factorial? The factorial of a number is the product of all the positive numbers less than or equal to n, indicated by n! According to the standard for an...

6 minutes read.

Constructor Overloading

The program contains more than one constructor in a class with the same name, and different types of arguments are called constructor overloading. Calling of constructor depends on the number and types...

2 minutes read.

Stack in C++

Stack: The stack is a very popular data structure. It is the form of data structure that follows a particular order called FIFO(First-In-First-Out). In simple words, a stack is an Abstract...

4 minutes read.

Differences Between C Structures and C++ Structures

The below table clearly describes the differences between C and C++ programming languages Structures concepts where the core principle concepts like static members, data handling, pointers, access modifiers, the importance...

3 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

Sliding Window Technique in C++

Sliding Window Technique or Window Sliding Technique is a computational technique that is mainly used to reduce the use of nested loop and replace it with a single loop. It...

4 minutes read.

Const_cast in C++ Type Casting Operators

In this tutorial, we will learn enough about const cast in the most widely used programming language, C++, as well as type casting operations. C++ supports the four types of casting...

4 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

Default arguments in C++

Arguments in a function are defined as the values supplied when the function is called. The source is the values supplied, and the destination is the receiving function. Let us...

3 minutes read.

Swap numbers in C++

Swap numbers Swapping refers to interchanging values between two variables. Swapping is important and easy to understand programming logic in the world of coding. Though it is used in the programming...

4 minutes read.

std::distance() in C++

The primary function of std::distance is to facilitate the total number of elements if we have two iterators. It is defined inside the header files. It has both magnitude and...

2 minutes read.