0

I created an array of vector called ed outside of main, then I modified it in main using push_back, finally I called a function that used the array of vectors. But in the function it says the vector is empty (size()==0)

#include <cstdio>
#include <string.h>
#include <vector>

using namespace std;


int previ[100001], typ[100001], lvl[100001];
vector<int> ed[100001];

void add(int toadd, int pre, int lv){
    previ[toadd] = pre;
    lvl[toadd] = lv;
    printf("%d\n", ed[0].size());//prints out 0
    for(int &a: ed[toadd]){
        //printf("%d\n", a);
        if(previ[a] = -1){
            add(a, toadd, lv + 1);
        }
    }
}


int main(){
    FILE *fi = fopen("milkvisits.in", "r"), *fo = fopen("milkvisits.out", "w");
    int n, m;
    fscanf(fi, "%d %d", &n, &m);
    vector<int> ed[n];
    memset(previ, -1, sizeof previ);
    for(int a = 0; a < m; a ++){
        fscanf(fi, "%d", &typ[a]);
    }
    int ta, tb;
    for(int a = 1; a < n; a ++){
        fscanf(fi, "%d %d", &ta, &tb);
        ta--; tb --;
        ed[ta].push_back(tb);
        ed[tb].push_back(ta);
    }
    
    printf("%d\n", ed[0].size());//prints out 2
    add(0, -2, 1);//inside the function it prints the size as 0
    printf("%d\n", ed[0].size());//prints out 2
    
    fclose(fi);
    fclose(fo);
    return 0;
}

Here is the input file milkvisits.in I used:

5 5
1 1 2 1 2
1 2
2 3
2 4
1 5
1 4 1
1 4 2
1 3 2
1 3 1
5 5 1
Bence Kaulics
  • 7,066
  • 7
  • 33
  • 63
Alvin
  • 5
  • 1
  • 2
  • 7
    The global variable named `ed` is distinct from and unrelated to the local variable also named `ed` declared inside `main`. `main` populates the latter; `add` accesses the former. – Igor Tandetnik Dec 19 '20 at 15:43
  • [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Gary Strivin' Dec 19 '20 at 15:54
  • It looks like you declared an array of vectors. Probably not what you intended. – Zan Lynx Dec 19 '20 at 16:25
  • `if(previ[a] = -1)` this condition is always true, and assigns the value `-1` to `previ[a]`. That's not usually what's needed. – Pete Becker Dec 19 '20 at 17:58

1 Answers1

0

Remove the line:

vector<int> ed[n];

in your main() function. This line declares the local vector, which is used only in main.

VillageTech
  • 1,968
  • 8
  • 18