我试图创建一个类名顶点的向量。 " n"的价值在编译时不知道所以我将使用new来创建以创建"路径"阵列。但是当我在函数中创建输入数组并将其推入向量中时会出现问题。
int n;
class vertex {
public:
int *path;
int visited = 0;
vertex(int *y) {
path = new int(n);
for (int i = 0; i < n; i++)
path[i] = y[i];
}
};
void inp(vector<vertex> graph) {
int t1[] = { 0,1,0,0 };
int t2[] = { 0,0,1,0 };
int t3[] = { 0,0,0,1 };
int t4[] = { 0,0,0,0 };
graph.push_back(vertex(t1));
graph.push_back(vertex(t2));
graph.push_back(vertex(t3));
graph.push_back(vertex(t4));
}
int main() {
n=4;
vector<vertex> graph;
inp(graph);
_getch();
}
为简单起见,我将t1创建为t4作为静态数组。但它仍然在运行时显示一些错误
答案 0 :(得分:1)
1:尝试使用:path = new int [n]
,而不是path = new int(n)
;
2:如果您想将元素推送到图表,则应将功能inp
更改为void inp(vector<vertex>& graph)