I have a simple, easy to understand question for you guys : What make this lambda function failed to even compile ?
int N; cin >> N;
vt<int> adj[N+1]; // I define vector as vt
FOR(N-1) { // for (int i = 0; i < N-1; i++)
int u, v; cin >> u >> v;
adj[u].pb(v); // pb is a shortcut for push_back
adj[v].pb(u);
}
// remember to check for case n = 1
vt<int> d(N+1);
auto dfs = y_combinator([&](auto dfs, int u, int p, int &r) {
if (u == p) d[u] = 0;
if (d[u] > d[r]) r = u;
each(v, adj[u]) if (v != p) { // each = for (auto &v : adj[u])
d[v] = d[u]+1;
dfs(v, u, r);
}
});
The thing is, when I'm trying to compile it, I received this catastrophic message :
sol.cpp: In function 'int main()':
sol.cpp:67:29: error: use of deleted function 'main()::<lambda(auto:1, int, int, int&)>::~<lambda>()'
67 | auto dfs = y_combinator([&](auto dfs, int u, int p, int &r) {
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
68 | if (u == p) d[u] = 0;
| ~~~~~~~~~~~~~~~~~~~~~
69 | if (d[u] > d[r]) r = u;
| ~~~~~~~~~~~~~~~~~~~~~~~
70 | each(v, adj[u]) if (v != p) {
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
71 | d[v] = d[u]+1;
| ~~~~~~~~~~~~~~
72 | dfs(v, u, r);
| ~~~~~~~~~~~~~
73 | }
| ~
74 | });
| ~
sol.cpp:67:31: note: 'main()::<lambda(auto:1, int, int, int&)>::~<lambda>()' is implicitly deleted because the default definition would be ill-formed:
67 | auto dfs = y_combinator([&](auto dfs, int u, int p, int &r) {
| ^
So I try a small fix by capturing 2 vector name d
and adj
, and it compile as intended ...
int N; cin >> N;
vt<int> adj[N+1]; // I define vector as vt
FOR(N-1) { // for (int i = 0; i < N-1; i++)
int u, v; cin >> u >> v;
adj[u].pb(v);
adj[v].pb(u);
}
// remember to check for case n = 1
vt<int> d(N+1);
auto dfs = y_combinator([&d, &adj](auto dfs, int u, int p, int &r) { // <----------- notice this line
if (u == p) d[u] = 0;
if (d[u] > d[r]) r = u;
each(v, adj[u]) if (v != p) { // each = for (auto &v : adj[u])
d[v] = d[u]+1;
dfs(v, u, r);
}
});
Obviously there is a very big question from my perspective : Why did the first piece of code that I used to capture everything in side the main()
function failed, but the second one work ? Is there any way around this, cus I don't want to spend time capturing variable ...
This is my code for y_combinator
Edit : Now I have a clearer version of this question at this link, pls visit it if you find these macros in my code here confusing.
Edit2 : Oops, this question has been answered on stackoverflow. You can view the answer using the above link.