# Storing Nodes With Parents In A Vector

This topic is 4247 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Ok I'm just screwin around with a test I've made to keep a vector of nodes. Each node has a parent and after I've created a vector of nodes I'd like to traverse from the last node to the front using each nodes parent. Here's my test:

class Node
{
public:
int Data;
Node* Parent;

Node() : Data(0), Parent(0)
{}

Node(int Data, Node* Parent)
{
Node::Data = Data;
Node::Parent = Parent;
}
};

int main()
{
std::vector<Node> NodeVector;

Node First;
NodeVector.push_back(First);

for(int i = 0; i < 10; i++)
{
NodeVector.push_back(Node(i, &NodeVector));
}

std::cout << NodeVector.size() << std::endl;

Node Current;
Current = NodeVector.back();
while(Current.Parent != 0)
{
std::cout << Current.Data << std::endl;
Current = *(Current.Parent);
}

std::cin.ignore();

return 0;
}


Problem: Output is 11(the length) 9 8 and that's it (Current.Parent == 0 after 2 iterations) So this obviously doesn't work. I know why, when I push a new node onto NodeVector and pass the previous elements address as the parent of this node, that's as far as it get's. The parent of the node I just pushed on has a parent = 0, as if it has just been created. But I don't understand why. Shouldn't passing the address of the previous node make this node's parent point to it, which, in turn will point to it it's parent etc. This is fustrating cause I know why this doesn't work but I can't figure out the "reason" why. Is there a way to make this work or is this just an exercise in silliness?

##### Share on other sites
Don't use pointers to vector elements when the vector may be resized during the lifetime of the vector (as happens here). You probably shouldn't use them at all, but instead vector indices (or something other kind of handle, depending on what kind of reorderings of stuff are allowed within the vector). The problem is that when the vector resizes, it reallocates new storage, copies stuff across to the new storage, and destroys the previous storage. It has to do this in order to guarantee the other behaviour that it provides, specifically of storing things in a single chunk (it couldn't just leave the data where it is and "increase the size of the current chunk", because the memory just "beyond" the current chunk could already be in use by something else.)

Of course, if 'nodes' make sense for whatever it is you're doing, maybe you should be working with a list rather than a vector. Oh, and you clearly know about initializer lists, so why aren't you using one for the 2-arg constructor? :)

##### Share on other sites
Thanks alot for your help, that makes perfect sense.

Also I have no idea why I'm not using an initalizer list for the other constructor. I feel kinda silly for not though, now that you've pointed it out.