Structured Bindings in C++

Sohini Dhar
3 min readJul 22, 2021

--

C++17 Advanced Features

C++17 had introduced another interesting feature which is easy to write, easy-to-use, and understand feature called Structured Bindings. “They are used to bind specific names to subobjects or elements of the initializer. In simple words, they give us the ability to declare multiple variables from a tuple or struct.” The syntax for Structured bindings as per cppreference are as follows:

auto ref [identifier-list] = expression; --------- (1)
auto ref [identifier-list] { expression };-------- (2)
auto ref [idenitifier-list]( expression );-------- (3)

Let me give you an example to show how this can be used in actual production code. Consider we need to find the frequency of each character in a string. One of the ways to solve the problem would be using hash maps or unordered maps as per C++ terminology.

#include <iostream>
#include <unordered_map>
int main()
{
std::string content{"aaadgsfjiiiowq"};
std::unordered_map<char, int> H{};
for(const auto& ch : content)
{
H[ch]++;
}
//Now in order to print the frequency of each character we need to loop over the hashmap H which can be done using structured bindings
for(const auto& [i,j] : H) // Here i stands for the key and j the
{ value in H
std::cout << i << " " << j << "\n";
}
return 0;
}

Output:

o  1
i 3
w 1
j 1
f 1
s 1
g 1
q 1
d 1
a 3

Note that since we are using unordered maps the output is not sorted. Also as an advantage of structured bindings, if we had not used them, the for loop would look something like this:

for(auto& it = H.begin();it!=H.end();it++)
{
cout << it->first << " " << it->second << "\n";
}

The above snippet would generate the same result, but as you can see structured bindings are simpler to write. This was a case of pairs, imagine you are working with a tuple and you can use the same concept. This will definitely make the code simpler, easily readable, and understandable.

A very highly experienced C++ professional provided me the feedback that I missed out on a very important feature/use of Structured Bindings. It's the way function can return multiple values. Thus I am adding/editing this section after publication. The example below will explain how returning multiple values from a method will actually look like.

#include <iostream>
#include <cmath>
#include <utility>
struct Complex
{
Complex(float r, float i) : real(r), imaginary(i)
{
}
friend std::ostream& operator<<(std::ostream& os, const Complex& c)
{
return os << c.real << " + " << c.imaginary << "i" <<"\n";
}
float real;
float imaginary;
};
std::pair<Complex, double> getMagnitudeOfComplexNum()
{
Complex c(3.4,7.8);
double mag = sqrt(pow(3.4,2) + pow(7.8,2));
return std::make_pair(c, mag);
}
int main()
{
const auto& [ cnumber, magnitude] = getMagnitudeOfComplexNum();
std::cout << "Complex Number is " << cnumber;
std::cout << "magnitude of Complex Number is " << magnitude << "\n";
return 0;
}

Output

Complex Number is 3.4 + 7.8i
magnitude of Complex Number is 8.50882

This is definitely not the best example, but I think the intention will be clear. As you can see in the main function we have used structured bindings to bind the first and second values which are returned from the function getMagnitudeOfComplexNum(). Similarly, suppose there is a class called Human and you need the name and age but it contains a lot of other properties and you need in a method you can use the same procedure. This prevents the author from using the words first and second repeatedly in their code and improves the chances of making mistakes.

For more uses, you check out more examples over the internet and use them more and more with your production code.

HAPPY C++ CODING!!! Please follow, like, comment, share if you like this.

--

--

Sohini Dhar
Sohini Dhar

Written by Sohini Dhar

Programmer, Traveler, Adventurer!!!!

No responses yet