5

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
}
Vasile Lup
  • 61
  • 1
  • 4

2 Answers2

6

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.

flowit
  • 1,382
  • 1
  • 10
  • 36
0

Structured bindings is what you are looking for, otherwise you can make

template <typename T, typename N>
struct pair 
{ 
    T first; 
     N second; 
};

and iterate the C way, assuming your types can be copied, moved , assigned, etc.

Ilian Zapryanov
  • 1,132
  • 2
  • 16
  • 28