Skip to content
Justice Tech School

Structured Bindings and if init

Structured bindings unpack pairs, tuples and structs into variables. if and switch can have an initialiser (C++17).

Example
map<string, int> ages = {{"Ada", 21}, {"Tunde", 30}};
for (auto [name, age] : ages) cout << name << "=" << age << " ";
cout << "\n";
pair<int, string> p{1, "one"};
auto [id, label] = p;
cout << id << label << "\n";
if (auto it = ages.find("Ada"); it != ages.end()) cout << it->second << "\n";

Result

Ada=21 Tunde=30 
1one
21

Exercise

Unpack a pair.

auto [a, b]  p;

Quiz Test

What do structured bindings do?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.