Spartan-007's blog

By Spartan-007, history, 2 hours ago, In English

Hello Codeforcers!

I'm encountering an issue with a recursive lambda DFS function in my code. Everything was working fine before, but now, after adding this function, I get an error. Can someone help me debug this and find out what's going wrong?

Thanks!

Code :-

    int n; cin >> n;
    vector<int> g[n];
    for(int i=1; i<n; ++i) {
        int u, v; cin >> u >> v;
        u--; v--;
        g[u].push_back(v);
        g[v].push_back(u);
    }

    string s; cin >> s;

    vector<int> leaf;
    auto dfs = [&](auto &&self, int u, int par) {
        for(auto &x : g[u]){
            if(x==par) continue;
            self(self, x, u);
        }
        if(g[u].size() == 1) leafs.push_back(u);
    };
    dfs(dfs,0,-1);

Error :

E:\Programming\cp\Sublime_Files\Hi.cpp: In function 'void solve()':
E:\Programming\cp\Sublime_Files\Hi.cpp:90:16: error: use of deleted function 'solve()::<lambda(auto:1&, ll, ll)>::~<lambda>()'
     auto dfs = [&](auto &self, ll u,ll par) {
                ^
E:\Programming\cp\Sublime_Files\Hi.cpp:90:18: note: 'solve()::<lambda(auto:1&, ll, ll)>::~<lambda>()' is implicitly deleted because the default definition would be ill-formed:
     auto dfs = [&](auto &self, ll u,ll par) {
                  ^
[Finished in 283ms]
  • Vote: I like it
  • 0
  • Vote: I do not like it

»
2 hours ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by Spartan-007 (previous revision, new revision, compare).

»
109 minutes ago, # |
  Vote: I like it +3 Vote: I do not like it

Try changing the line vector g[n] to vector<vector> g(n) and add return type for the function definition.

  • »
    »
    105 minutes ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Very much thanks for this. This worked !!

    But still just curious about why primitive arrays don't work with this style of writing recursive lambdas.

    • »
      »
      »
      93 minutes ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      I don't exactly know why it doesn't work, but the thing you used is called VLA (Variable length Array) and is some sort of extension of GCC. VLA is kinda weird and things like what you just experienced can happen. I suggest just not using it.

    • »
      »
      »
      92 minutes ago, # ^ |
        Vote: I like it +3 Vote: I do not like it

      Variable length arrays are not valid C++, only a GNU extension.