我想在C++中使用动态数组(类似于Java中的ArrayList或Vector)。
在这个例子中,t1, t2等对象是被复制还是仅添加了它们的地址到向量中?
我需要为Node类实现一个拷贝构造函数吗?还是默认构造函数会生成一个“适当”的副本(因为类中有指针)?
或者我只需声明一个
并且我是否需要实现一个析构函数来删除
在这个例子中,t1, t2等对象是被复制还是仅添加了它们的地址到向量中?
我需要为Node类实现一个拷贝构造函数吗?还是默认构造函数会生成一个“适当”的副本(因为类中有指针)?
或者我只需声明一个
vector<Node*>
以避免复制?并且我是否需要实现一个析构函数来删除
other_node
指针,或者它可以被程序使用并仍然存储在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;
}
std::vector
,所以最好使用std::cout
。 - Alan