I'm trying to write a generic doubly-linked tree (or some variation of that, i guess)
This is the code for adding a node to another already present node.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Node<T>* addNode(Node<T>* linkTo)
{
//Create new node, add it to total nodes.
Node<T> newNode;
nodes.push_back(newNode);
//Create a pointer to back of the vector.
Node<T> *newPointer;
newPointer = &nodes.back();
//Set previous node to parameter pointer
newPointer->previous.push_back(linkTo);
//Set parameter pointer's next to our node
linkTo->next.push_back(newPointer);
return newPointer;
}
In the main() function:
1 2 3 4 5
Tree<int> a;
//createRoot() is the same as addNode(), except it doesnt take arguments
//and doesnt link any nodes together
Node<int> *pointerlel = a.createRoot();
Node<int> *anthrptrlel = a.addNode(pointerlel);
Sometimes, it will work. Sometimes it randomly hangs forever. Any idea what might be wrong?
Additional notes: If i delete the line containing addNode(), or createRoot(), the program doesn't hang randomly anymore. They are mutually exclusive apparently.
Also, should I be using smart pointers or something?
#ifndef TREE_H
#define TREE_H
#include "Node.h"
template <class T>
class Tree
{
public:
vector<Node <T> > nodes;
Node<T>* createRoot()
{
//Create a new, empty node, and add it to the node vector.
Node<T> newNode;
nodes.push_back(newNode);
//Return a pointer that points to the area in mmry in vector;
Node<T> *newPointer;
newPointer = &nodes.back();
return newPointer;
}
Node<T>* addNode(Node<T>* linkTo)
{
//Create new node, add it to total nodes.
Node<T> newNode;
nodes.push_back(newNode);
//Create a pointer to back of the vector.
Node<T> *newPointer;
newPointer = &nodes.back();
//Set previous node to parameter pointer
newPointer->previous.push_back(linkTo);
//Set parameter pointer's next to our node
linkTo->next.push_back(newPointer);
return newPointer;
}
};
#endif // TREE_H
A vector invalidates iterators and/or pointers to elements when it needs to expand, so the address obtained on line 30 may become invalid later in the program.