1

A common pattern I like to use in python is to have a recursive function within a function. For example a short recursive way to find all possible subset sums of an array:

def all_sums(arr):

    res = set()
    def dfs(index, current_sum):
        if index == len(arr): 
            res.add(current_sum)
            return
        dfs(index + 1, current_sum + arr[index])
        dfs(index + 1, current_sum)
    dfs(0, 0)
    return res

This is very nice and simple so I was wondering if there is a way to reproduce this in C++. I've saw this question, so I tried something like so:

# include<bits/stdc++.h>
using namespace std;

unordered_set<int> all_sums(vector<int> &arr){
    unordered_set<int> res;
    auto dfs = [&](int index, int current_sum){
        if(index == arr.size()){
            res.insert(current_sum);
            return;
        }
        dfs(index + 1, current_sum + arr[index]);
        dfs(index + 1, current_sum);
    };
    dfs(0, 0);
    return res;
}

This fails because dfs can't appear in it's own initializer. I'm wondering if there is a nice way to have the "recursive function within function" functionality in C++.

4
  • You can declare dfs as std::function<void(int, int)> instead of auto. Commented Jan 10, 2020 at 4:37
  • @NicoSchertler oh that was fast, would you care to make it an answer so I can accept? Commented Jan 10, 2020 at 4:38
  • @Evg thank you, this is appreciated, I should have googled with the keyword "lambda" Commented Jan 10, 2020 at 4:43
  • You could use an explicit functor class instead of a lambda. Commented Jan 10, 2020 at 4:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.