【发布时间】:2013-06-28 05:00:37
【问题描述】:
有人可以告诉我以下代码有什么问题吗?我正在尝试实施 具有类 Node 的图,其中包含节点 id 和指向其邻居的指针向量。这是我的代码的简短版本:
#include<vector>
#include<iostream>
using namespace std;
class N {
public:
int i;
vector<N*> v;
N(int i) {
this->i = i;
};
};
int init(N* n1) {
N n2(2);
cout << "pointer " << &n2 << endl;
n1->v.push_back(&n2);
};
int main() {
N n1(1);
init(&n1);
cout << n1.i << endl;
cout << "pointer " << n1.v[0] << endl;
cout << n1.v.at(0)->i << endl;
return 0;
};
问题是调用init函数后,节点n2好像不存在了。
感谢您的帮助。
【问题讨论】:
-
运行程序时会发生什么?输出与您的预期有何不同?
标签: c++ pointers constructor