我想在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