I've came across the following code:
vector<pair<int, int>> vec;
//...
for (auto &[f, s] : vec)
{
//do something with f and s
}
how does this syntax work ([f, s] : vec) and since what standard was it introduced? Can I use it for getting field values from any struct/class or is it something specific to tuple/pairs?
Also, what is the performance impact of this approach?
In C++11 I was using auto in the following way:
for (auto &it : vec)
{
//do something with it.first and it.second
}
What you see here are structured bindings. For a full explanation of this feature see https://en.cppreference.com/w/cpp/language/structured_binding. Structured bindings were introduced in C++17. They provide a new syntax to give identifiers to members of a type.
In general, you can use structured bindings with your own types, too, but that requires a bit more effort. By default, arrays, tuple-like objects and aggregates are supported.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With