0

The following is a Java implementation of union-find, and I wish to replicate the same in C++:


class v_rank{
    int position, rank;
    v_rank parent;
    public v_rank(int position){
        this.position = position;
        rank = 0;
        parent = null;
    }
}
static v_rank find(v_rank v){
    if(v.parent == null)
        return v;
    v.parent = find(v.parent);
    return v.parent;
}

static void union(v_rank root1, v_rank root2){
    if(root1.rank < root2.rank)
        root1.parent = root2;
    else if(root1.rank > root2.rank)
        root2.parent = root1;
    else{
        root2.parent = root1;
        root1.rank++;
    }
}

What I tried for C++:

struct vert {
    int pos, rank;
    vert* par;
    vert(int pos) {
        this->pos = pos;
        rank = 0;
        par =  NULL;
    }
};

vert find(vert v) {
    if (v.par == NULL)
        return v;
    *(v.par) = find(*(v.par));
    return *(v.par);
}

Unlike java with such an implementation I cannot compare 2 vert with a simple '=='. I need to make a pair of 2 such verts and then a vector of all such pair (edges). I'm having issues with that as well.

Can someone suggest a way to replicate java code in cpp, such that I'm able to check for equality of two 'verts' and use a vector of pairs of 'verts'?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Karmah24
  • 485
  • 1
  • 5
  • 14
  • Why do you want to chek for equality of two 'verts' ? and what do you mean by a vector of pairs of 'verts' ? can you elaborate more ? – Maaddy Oct 21 '20 at 16:06
  • @Maaddy a union must be done if 2 'verts' belong to the same set. Hence, I have to check for the equality of the root 'verts'. and these 'verts' (vertices) need to paired up to form edges and I need a list of all such edges hence a vector of pairs of 'verts'. – Karmah24 Oct 21 '20 at 16:15
  • Even in Java you can't compare 2 objects with a simple '==' I still don't understand what's your problem here, are you stuck with the implementation of the union method ? and why do you want the edges ? the edges are useless in a union-find structure, the important data is each tree's parent in the forest of the union-find. Can you please explain where is the problem exactly so I can help you ? – Maaddy Oct 21 '20 at 17:26
  • 1
    @Maaddy can I email you or something? – Karmah24 Oct 22 '20 at 03:27
  • yes :) you can ofc. Look for me on linkedin under the name "Mahdy Berriri" and message me, and I'll give you my email there :) – Maaddy Oct 22 '20 at 13:19

0 Answers0