0

I am trying to generate all subsets of the set {1,2,3} recursivley. When I run the code though, nothing is printed. I add elements into the vector but printing the vector gives me nothing. Am I not printing in the right place or is something else going on?

#include <stdio.h>
#include <vector>
#include <iostream>
using namespace std;

int n=3;

void gen(int k) {
    vector<int> v;
    if (k == n + 1) {
        cout <<"(";
        for (auto i = v.begin(); i != v.end(); ++i){
            cout << *i ;
        }
        cout <<")";
    }
    else {
        gen(k + 1);
        v.push_back(k);
        gen(k + 1);
        v.pop_back();
    }
}

int main(){
    gen(1); 
    return 0;
}
ATidedHumour
  • 183
  • 3
  • 9
  • Note that `vector v;` in `main()` isn't the same as you access in your function. Also there's a new instance of `v` whenever you call `gen()` recursively. – πάντα ῥεῖ Oct 18 '18 at 21:17
  • yes, I just forgot that in the code, i'm not using the one in the main function.I'll edit it out. – ATidedHumour Oct 18 '18 at 21:18
  • https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h –  Oct 18 '18 at 21:18
  • 1
    Probably not related to question, but `#include ` and `using namespace std;` together are a great way to give yourself a huge headache. – Yksisarvinen Oct 18 '18 at 21:19
  • Oh ok, thanks I didn't know that. I'll try to get rid of it.Edit: I replaced the #include with #include #include #include – ATidedHumour Oct 18 '18 at 21:21

1 Answers1

0

Your issue is that the vector v in gen is a function local object so each call to gen has its own v. That isn't what you want since you want all the recursive calls to populate the same v.

You have a couple ways to fix that. You could make v static but then you could only call the function once. You could make v a global variable but then you need to remember to call clear() on then vector after each time you run gen. Lastly, you can make a helper function that declares the vector and then passes it to your recursive function to use. This IMHO is the more correct solution as it requires no user intervention. That would give you

void gen(int k, std::vector<int>& v) {
    if (k == n + 1) {
        cout <<"(";
        for (auto i = v.begin(); i != v.end(); ++i){
            cout << *i ;
        }
        cout <<")";
    }
    else {
        gen(k + 1, v);
        v.push_back(k);
        gen(k + 1, v);
        v.pop_back();
    }
}

void gen(int k) {
    vector<int> v;
    gen(k, v);
}

int main(){
    gen(1);
    return 0;
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402