Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ iterate over vector of pairs with destructuring

Tags:

c++

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
}
like image 409
Vasile Lup Avatar asked Jan 12 '20 15:01

Vasile Lup


1 Answers

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.

like image 131
flowit Avatar answered Sep 28 '22 17:09

flowit