Structured binding in C++
Last Updated :
07 May, 2018
Prerequisite : Tuples in C++
Structured binding is one of the newest features of C++17 that binds the specified names to subobjects or elements of initializer. In simple words, Structured Bindings give us the ability to declare multiple variables initialized from a tuple or struct. The main purpose of Structured Bindings in C++ 17 is to make the code clean and easy to understand. Like a reference, a structured binding is an
alias to an existing object. Unlike a reference, the type of a structured binding
does not have to be a 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);
Parameters :
- auto : auto
- ref operator : either & or &&
- identifier-list : List of comma separated variable names.
- expression : An expression that does not have the comma operator at the top level (i.e, an assignment-expression), and has either array or non-union class type.
Basic Type Deduction :
Let
E denote the type of the
initializer expression. E shall be either a specialization of
std::tuple, or a type whose non-static data members are all accessible and are declared in the same base class of E. A structured binding declaration performs the binding in one of three possible ways, depending on E.
- Case 1 : if E is an array type, then the names are bound to the array elements.
- Case 2 : if E is a non-union class type and tuple_size is a complete type, then the "tuple-like" binding protocol is used.
- Case 3 : if E is a non-union class type but tuple_size is not a complete type, then the names are bound to the public data members of E.
Let us see the advantage of Structure bindings over tuples with the help of an example :
Example 1 : In C++98
CPP
#include <bits/stdc++.h>
using namespace std;
// Creating a structure named Point
struct Point {
int x;
int y;
};
// Driver code
int main()
{
Point p = {1, 2};
int x_coord = p.x;
int y_coord = p.y;
cout << "X Coordinate : " << x_coord << endl;
cout << "Y Coordinate : " << y_coord << endl;
return 0;
}
Output :
X Coordinate : 1
Y Coordinate : 2
Example 2 : In C++11/C++14
CPP
#include <bits/stdc++.h>
#include <tuple>
using namespace std;
// Creating a structure named Point
struct Point
{
int x, y;
// Default Constructor
Point() : x(0), y(0)
{
}
// Parameterized Constructor for Init List
Point(int x, int y) : x(x), y(y)
{
}
auto operator()()
{
// returns a tuple to make it work with std::tie
return make_tuple(x, y);
}
};
// Driver code
int main()
{
Point p = {1, 2};
int x_coord, y_coord;
tie(x_coord, y_coord) = p();
cout << "X Coordinate : " << x_coord << endl;
cout << "Y Coordinate : " << y_coord << endl;
return 0;
}
Output :
X Coordinate : 1
Y Coordinate : 2
Example 3 : In C++17
CPP
#include <bits/stdc++.h>
using namespace std;
struct Point
{
int x;
int y;
};
// Driver code
int main( )
{
Point p = { 1,2 };
// Structure binding
auto[ x_coord, y_coord ] = p;
cout << "X Coordinate : " << x_coord << endl;
cout << "Y Coordinate : " << y_coord << endl;
return 0;
}
Output :
X Coordinate : 1
Y Coordinate : 2
Applications : Structured Binding can be used with arrays to get the elements from the array. In this case, E is an array type, hence the names are bound to the array elements. Below is the implementation to show the same :
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[3] = { 1, 2, 3 };
// Here, E is an array type, hence the
// names are bound to the array elements.
auto[x, y, z] = arr;
cout << x << " " << y << " " << z << endl;
return 0;
}
Output :
1 2 3
Note : The number of identifiers in the identifier list must be equal to the number of elements in the array. If the number of identifiers in the identifier list is less, then either a compile time error or design time error may occur. This means that we cannot take the specific set of elements from the array.
A more practical example for using the structured bindings is as follows :
CPP
#include <bits/stdc++.h>
#include <map>
using namespace std;
int main()
{
// Creating a map with key and value
// fields as String
map<string, string> sites;
sites.insert({ "GeeksforGeeks", "Coding Resources" });
sites.insert({ "StackOverflow", "Q-A type" });
sites.insert({ "Wikipedia", "Resources + References" });
for (auto & [ key, value ] : sites)
{
cout << key.c_str() << " " << value.c_str() << endl;
}
return 0;
}
Output :
GeeksforGeeks Coding Resources
StackOverflow Q-A type
Wikipedia Resources + References
Note : Qualifiers such as
const and
volatile can be used along with type to make the declaration variable constant or volatile.
For more details on Structured bindings, you may refer :
P0144R0
Similar Reads
Structures in C++ C++ Structures are used to create user defined data types which are used to store group of items of different data types.SyntaxBefore using structure, we have to first define the structure using the struct keyword as shown:C++struct name{ type1 mem1; type2 mem2; ... };where structure name is name an
8 min read
C++ - Pointer to Structure Pointer to structure in C++ can also be referred to as Structure Pointer. A structure Pointer in C++ is defined as the pointer which points to the address of the memory block that stores a structure. Below is an example of the same: Syntax: struct name_of_structure *ptr; // Initialization of structu
2 min read
Trie Data Structure in C++ A Trie, also known as a prefix tree, is a tree-like data structure used to store a dynamic set of strings. It is particularly useful for efficient retrieval of keys in a large dataset of strings. In this article, we will explore the Trie data structure, its operations, implementation in C++, and its
8 min read
Difference Between Structure and Class in C++ In C++, a structure works the same way as a class, except for just two small differences. The most important of them is hiding implementation details. A structure will by default not hide its implementation details from whoever uses it in code, while a class by default hides all its implementation d
3 min read
Balanced Binary Tree in C++ A Balanced Binary Tree, also known as a height-balanced binary tree, is a binary tree in which the height of every node's left and right subtrees differs by at most one. This balance condition ensures that the tree maintains a logarithmic height, which in turn guarantees O(log n) time complexity for
8 min read
Policy based data structures in g++ The g++ compiler also supports some data structures that are not part of the C++ standard library. Such structures are called policy-based data structures. These data structures are designed for high-performance, flexibility, semantic safety, and conformance to the corresponding containers in std.To
6 min read
Structures, Unions and Enumerations in C++ Structures, unions and enumerations (enums) are 3 user defined data types in C++. User defined data types allow us to create a data type specifically tailored for a particular purpose. It is generally created from the built-in or derived data types. Let's take a look at each of them one by one.Struc
3 min read
Fork CPP | Course Structure Course Home Page Week Topic Sub-Topic Week 1 Basics Of C++, Control Structures Syntax, Variables, Data Types, I/O, Operators, Preprocessors, If, If-else, Switch case, Loops(For, While, Do while) Week 2 Arrays, Bitwise Operators, Strings, Functions 1D-array(creation, updation, deletion), 2D-array(cre
1 min read
Difference Between C Structures and C++ Structures Let's discuss, what are the differences between structures in C and structures in C++? In C++, structures are similar to classes. Differences Between the C and C++ StructuresC Structures C++ Structures Only data members are allowed, it cannot have member functions.Can hold both: member functions and
6 min read
Segment Tree in C++ A Segment Tree is a data structure that is used for various range query problems, particularly in competitive programming. It allows for efficient query operations on arrays, such as finding the minimum, maximum, or sum of elements in a given range. In this article, we will learn how to implement a
7 min read