简体   繁体   中英

Initializing an Array C++

My code is trying to implement the union-find algorithm and I have the id[] array and the sz[] array. I initialize them in the Union-Find constructor, but once I try to use those arrays in the methods within the Union-Find class, it changes all the array values to 1. I don't understand why. Is there something obvious that I'm missing??

H File

class UnionFind{
public:
    UnionFind(int size);
    void join(int x, int y);
    int connected(int x, int y);
    int find(int x);

private:

    int size;
    int id[];
    int sz[];

};

CPP File

UnionFind::UnionFind(int size){
        this->id[size] = id[size];
        for(int i = 0; i < size; i++){
            id[i] = i;
        }
        for(int i = 0; i < size; i++){
            sz[i] = 1;
        }
    }

    int UnionFind::find(int l){
        //Path Compression Finding the Root
        for(int i = 0; i < 5; i++){
        }
        while(l != id[l]){
            id[l] = id[id[l]];
            l = id[l];
        }
        return l;

    }

    void UnionFind::join(int x, int y){
        int m = find(x);
        int n = find(y);

        if(sz[m] < sz[n]){
            id[m] = n;
            sz[n] += sz[m];
        }
        else{
            id[n] = m;
            sz[m] += sz[n];
        }
    }

    int UnionFind::connected(int x, int y){
        if(find(x) == find(y)){
            return 1;
        }
        else{
            return 0;
        }
    }

From the comments.

  • you can't have int id[] as a class member,
  • use std::vector (resize and fill in constructor),
  • your forgot to set member size in constructor,
  • your find algorithm uses path halving not path compression (this does not affect the running time).

Side note: you can use a single array/vector to implement your disjoint set data structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM