In C++, is it possible for a function to access variables which were not provided in argument but defined in main()?

Viewed 17

I defined a vector<int> subset in main. To remove the two annotated errors in the code below, must I put subset and n as argument of function search?

#include <bits/stdc++.h>
#define F first
#define S second
#define PB push_back
#define pB pop_back
#define MP make_pair
#define REP(i, a, b) for (int i=a; i<=b; i++)

using namespace std;

void search(int k) {
    if (k == n+1) {     // [Error 1] how should I let this function recognize n from main?
        // process subset
    } else {
        // include k in the subset
        subset.PB(k);   // [Error 2] how do i fix an undefined error from here?
        search(k+1);
        subset.pB();
        // don't include k in the subset
        search(k+1);
    }
}

int main() 
{
    typedef long long ll;
    typedef vector<int> vi;
    vi subset;
    int n = 3;
    search(1);
    for (int i=0; i<n; i++) cout << subset[i] << "\n";
}
0 Answers
Related