在 C++ 中访问矩阵时崩溃
我正在尝试创建一个二维数组来表示加权图。为了制作矩阵,我制作了一个数组数组,如下面的构造函数所示。该矩阵将存储连接两个节点的边的权重。例如,graph[1][2] 将存储点 1 和 2 之间的边的权重。
Weighted_graph::Weighted_graph( int n ):vertices(n){
double **graph= new double *[vertices];
nodeDegree=new int [n];
edges=0;
for (int c=0;c<vertices;c++)
{
graph[c] = new double[vertices];
nodeDegree[c]=0;
for (int d=0;d<vertices;d++)
{
graph[c][d]=INF;
}
}
}
图形定义为 double **graph;
这似乎一直有效,直到我尝试访问该变量来自其他函数的图表,此时程序崩溃。 (INF 在代码中进一步定义)。
I'm trying to create a 2D array to represent a weighted graph. To make the matrix I am making an array of arrays, as shown in the constructor below. This matrix will store the weight of the edges connecting two nodes. For example graph[1][2] would store the weight of the edge between points 1 and 2.
Weighted_graph::Weighted_graph( int n ):vertices(n){
double **graph= new double *[vertices];
nodeDegree=new int [n];
edges=0;
for (int c=0;c<vertices;c++)
{
graph[c] = new double[vertices];
nodeDegree[c]=0;
for (int d=0;d<vertices;d++)
{
graph[c][d]=INF;
}
}
}
with graph defined as double **graph;
This seems to work until I try to access the variable graph from other functions at which point the program crashes. (INF is properly defined further down in the code).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您正在引用您正在构造的对象的图形成员。然而,graph 在那里被声明为局部变量。
I presume you are referencing the graph member of the object you are constructing. However, graph is declared as a local variable there.
这一切都与范围有关,因为您在一个函数中可以重复使用变量名,但这个变量只能在讲师中访问。删除构造函数中图表前面的 double**。
It's all about scope, because you are in a function you can re-use a variable name, but this one is only accessible in the instructor. Remove the double** from in front of graph in the constructor.
不要重新发明轮子。使用 boost::multi_array。
Don't reinvent the wheel. Use boost::multi_array.