C ++で動的配列(JavaのArrayListやVectorのようなもの)を使用したいのです
が、この例では、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;
}