Iterators and Struct

Hello,

A.is there a problem with this handling of this struct ?

struct Node
{
list<Node *> sons;
string value;
Node(string v);//Constructor for no sons
};


Function that uses this struct will have:
void somefunction(string father, string newval)
{
Node*place=search(root, father);//search is some function
Node *Newp;
Newp->value = newval;
}

B.Is it ok ? ,every organ is Node by itself and contains a List..

Node *t;
t->sons.begin();



C.Is there a problem with this iterator handling and this struct?:


void SomeOtherFunction(Node *p, int level)
{

list<Node *>::iterator it = (*p).sons.end();

*(it--);
}
Last edited on
A.is there a problem with this handling of this struct ?

struct Node
{
list<Node *> sons;
string value;
Node(string v);//Constructor for no sons
};
Looks good.

Function that uses this struct will have:
void somefunction(string father, string newval)
{
Node*place=search(root, father);//search is some function
Node *Newp;
Newp->value = newval;
}

B.Is it ok
Terrible. Newp is an uninitialized pointer.

every organ is Node by itself and contains a List..

Node *t;
t->sons.begin();
Now t is an uninitialized pointer.

C.Is there a problem with this iterator handling and this struct?:
void SomeOtherFunction(Node *p, int level)
{

list<Node *>::iterator it = (*p).sons.end();

*(it--);
}
Not always. It's probably better to use a reverse_iterator instead.
Is that you should initialize it ?

Newp->value = newval;
Newp->sons = { NULL };

Also in the Node struct there is actually a constructor to Node without sons (the list).
How to use it ?
Last edited on
Newp->value = newval;
Newp->sons = { NULL };

Where does Newp point to? For this code to work Newp must first point to a valid Node object.
Its suppose to be a new Node,last in list of Nodes,he should have the potential of pointer if he will be needed to point to some other Node in the progress.

You need to create a new Node object. To do this you might want to use the new keyword, but in that case you should not forget to delete the object when you are done with it (or you could use smart pointers).

1
2
3
// Creates a new Node object 
// that the Newp pointer will point to.
Node *Newp = new Node;
C.Is there a problem with this iterator handling and this struct?:
If (*p).sons is empty you will have an undefined behavior.
1
2
3
4
5
6
struct Node
{
list<Node *> sons;
string value;
Node(string v);//Constructor for no sons
};

How will the nodes in the sons list get deleted?

Your functions should probably be methods of struct Node.
Topic archived. No new replies allowed.