Structured Binding Declarations

This lesson sheds light on the modifications made to tuple functionality.

Do you often work with tuples or pairs?

If not, then you should probably start looking into those handy types. Tuples enable you to bundle data ad-hoc with excellent library support instead of creating small custom types. The language features like structured binding make the code even more expressive and concise.

Consider a function that returns two results in a pair:

std::pair<int, bool> InsertElement(int el) { ... }

You can write:

auto ret = InsertElement(...)

And then refer to ret.first or ret.second. However, referring to values as .first or .second is also not expressive - you can easily confuse the names, and it’s hard to read. Alternatively, you can leverage std::tie which will unpack the tuple/pair into local variables:

int index { 0 };
bool flag { false };
std::tie(index, flag) = InsertElement(10);

Such code might be useful when you work with std::set::insert which returns std::pair:

Get hands-on with 1400+ tech skills courses.