Question

I'm trying to write a tree construction program in c++. (it's McCreight's suffix tree) but i have problem with assignment operator overloading for Nodes, specifically of a pointer attribute within my class Node! I have this code in my tree construction method which is not working (explained below):

void ST::insert(int suffix, Node& leaf)
{
    .
    .
    .
    leaf=find_path(u.suffix);
    cout<<leaf.id<<" "<<leaf.parent->id<<'\n';
    .
    .
    .
}

Node ST::find_path(Node* node, int suffix)
{
    .
    .
    .
    cout<<leaf.parent->id<<'\n';
    return leaf;
}

The cout in find_path prints the correct parent id, but when returning the node to insert() it's parent is being lost. cout in insert prints the correct "leaf id" but it doesn't know the "leaf's parent id".

My code for Node class is like this:

class Node
{
public:
    int id;
    Node* parent;
    vector <Node> children;
    vector <int> startPointer;
    Node* SL;
    int strDepth;
    Node()
    {
        parent=NULL;
        SL=NULL;
    }

Node& operator=(const Node node2)
{
    this->id=node2.id;
    if(this != &node2 && node2.parent!=NULL && node2.SL!=NULL)
    {
        *parent = *(node2.parent);
        parent = (node2.parent);
        *SL=*(node2.SL);
    }
    this->children=node2.children;
    this->startPointer=node2.startPointer;
    this->strDepth=node2.strDepth;
}

I have tried many ways to change this overloaded operator but each way giving some other error (usually runtime like NullPointerException), the code I included here is the one which gives the best answer so far, but unless i find a way to know the parent of the returned node i can't finish this! of course i can return the parent and grandparent as separate nodes but that's not interesting. Any help is really appreciated. Thank you!

Was it helpful?

Solution

Use std::shared_pointerfor links to nodes, and std::weak_pointer for backlinks.

You might specialise shared_pointer for your class, so that the added bookkeeping data is stored in the node itself. Look at enable_shared_from_this<T>.

OTHER TIPS

Your assignment operator is not implemented correctly. Try this instead:

Node& operator=(const Node &node2)
{
    if(this != &node2)
    {
        this->id=node2.id;
        this->parent = node2.parent;
        SL=node2.SL;
        this->children=node2.children;
        this->startPointer=node2.startPointer;
        this->strDepth=node2.strDepth;
    }
    return *this;
}

In which case, you could just omit the operator altogether and let the compiler auto-generate a default operator for you, as it would generate the same code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top