While doing a project dealing with graph theory, I used objects like such:
class Node{
vector<Node> nodeList;
};
Node n = new Node();
Node a = new Node();
n.nodeList.push_back(a);
After creating about 20 nodes each with an average of 3 connections to other nodes, my program would basically hang.
To fix that, I changed my object declarations to
class Node{
vector<Node*> nodeList;
};
Node* n = new Node();
Node* a = new Node();
n.nodeList.push_back(a);
And my program ran through 50 nodes with 10 connections instantly.
The second example ran faster because I was just adding pointers to the lists, as opposed to the actual nodes, right?
But the C++ documentation says that the new
keyword returns a pointer to the created object. Why is the entire object put into the vector in the first example as opposed to just the pointer?
Is there any reason the standard in C++ is to copy the entire object into a data structure instead of a pointer?
EDIT: I apologize, you are right the first example should not compile. I don't have the first example anymore on my drive anymore, and I can't remember exactly how it was. Sorry.