我想在C++中使用动态数组(如ArrayList或Java中的Vector)
在此示例中,是否将t1,t2 ...对象复制或只将其地址添加到向量中?
我是否需要为Node类实现一个拷贝构造函数,或者默认的构造函数是否会创建一个“正确的”拷贝(因为这个类中有一个指针)?
或者我应该声明一个vector<Node*>
而不是这样来避免复制?
我是否必须实现一个析构函数来删除other_node
指针,或者它可以被程序使用并仍然存储在vector
?C++矢量复制元素?
#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;
}
只是一个提示,因为你使用'std :: vector',你应该更喜欢'std :: cout'。 – Alan 2010-07-23 22:25:58