I would like to use a dynamic array in C++ (something like an ArrayList or a Vector in Java.)
In this example are the t1, t2... objects are copied or only its address is added to the vector?
Do I need to implement a copy constructor for Node class or will the default constructor make a "proper" copy (because there is a pointer in the class)?
Or should I just declare a vector<Node*>
instead of this to avoid copying?
And do I have to implement a destructor to delete the other_node
pointer or may it be used by the program and still be stored in the vector
?
#include <vector>
using namespace std;
class Node {
public:
int id;
Node* other_node;
};
int main(int argc, char** argv) {
vector<Node> nodes;
Node t1;
t1.id = 0;
t1.other_node = NULL;
Node t2;
t2.id = 1;
t2.other_node = &t1;
Node t3;
t3.id = 2;
t3.other_node = &t2;
Node t4;
t4.id = 3;
t4.other_node = &t1;
nodes.push_back(t1);
nodes.push_back(t2);
nodes.push_back(t3);
nodes.push_back(t4);
for (vector<Node>::iterator it = nodes.begin(); it != nodes.end(); it++) {
if (it->other_node) {
printf("%d (other.id: %d)\n", it->id, it->other_node->id);
} else {
printf("%d (other.id: NULL)\n", it->id);
}
}
getchar();
return 0;
}