0

我已经阅读了有关 2d 动态数组的内容,但显然我还没有完全理解它,因为这个程序不起作用。该程序似乎在于显示数组。输入文件是一个文本文件,第一行有 V 和 E,它们之间有一个“制表符缩进”。输入顶点再次位于下一行的制表符上,每行都缩进了一个新集合。在 DevCpp 上,它说存在分段错误。任何帮助将不胜感激。谢谢。

#include <iostream>
#include <fstream>

using namespace std;

#define maxV 100
#define unseen 0

typedef int Vertex;

class Graph {
private:
   int V, E;
   int**adj;

public:
    Graph(char filename[]);
    void display();
};

// constructor ask you for file name
Graph::Graph(char fname[])  {
    Vertex u,v;
    int j;

    ifstream f;
    f.open(fname, ios::in);
    if(!f) {
       cout << "\nError: Cannot open file\n";
       return;
    }

    //Input number of vertices and edges
    f >> V >> E;

    int** adj = new int*[V];
    for (int i=0;i<=V;i++)
    {
       adj[i]= new int[V];
    } 

    for(int x=0;x<=V; ++x) // initially 0 array
    {
       for (int y=0;y<=V;++y) 
          adj[x][y] = 0;
    }                             

    // Set diagonal to 1 
    for(int z=0; z<=V; ++z) 
       adj[z][z]=1;

    for (j =0;j<=E;++j)
    {
        f>>u>>v;
        adj[u][v] = 1;
        adj[v][u] = 1;
    }
}

// This method displays the adjacency lists representation.
void Graph::display(){
   int a,b,c;
   for (a=0;a<=V;++a)
   {
      cout << a << "  ";
   }
   cout << endl;

   for (b=0;b<=V;++b)
   {
      cout << b << "| ";

      for (c=0;c<=V;++c)
      {
         cout<<adj[b][c]<<"| ";
      }
      cout<<endl;
   }
}

int main()
{
    char fname[20];
    cout << "\nInput name of file with graph definition: ";
    cin >> fname;

    Graph g(fname);
    g.display();
}
4

3 回答 3

3
//Input number of vertices and edges
f >> V >> E;

// You're hiding your member variable in the following line, leading to an incorrect initialization    
// int** adj = new int*[V];
adj = new int*[V];
for (int i=0;i<=V;i++)
{
    adj[i]= new int[V];
} 
于 2011-04-13T01:50:00.740 回答
0

我在初始化数据数组的代码中看到了两个重大问题。首先,像这样的循环

    for (int i=0;i<=V;i++)

循环一个比数组中实际存在的元素多一个的元素。如果数组长度为 V 个元素,则循环的正确形式是

for (int i=0;i<V;i++)

那是“小于”而不是“小于或等于”。

其次,您将指针数组分配为 V 指针长,而各个列也分配为 V 元素长;但后来您使用相同的数组并期望它的大小为 V x E。总而言之,我认为分配代码应该是

int** adj = new int*[V];
for (int i=0;i<V;i++)
{
   adj[i]= new int[E];
} 

其他地方可能还有其他错误,但至少我已经让你开始了。

于 2011-04-13T01:49:26.240 回答
0

我不知道哪条线导致了分段错误,但这里有一些事情要注意:

for (j =0;j<=E;++j)
{
    f>>u>>v;
    adj[u][v] = 1;
    adj[v][u] = 1;
}

是否u保证v小于V? 如果不是,您可能会在矩阵范围之外编写。

什么时候发生j == E?您正在尝试读取文件中最后一行之后的一行。您应该改为检查j < E. 更好的方法仍然是忽略E所有内容,然后执行以下操作:

while(f >> u >> v)
{
    adj[u][v] = 1;
    adj[v][u] = 1;
}

虽然分段错误更可能在这里:

for (b=0;b<=V;++b)
{
    cout<<(b+1)<<"| ";
    for (c=0;c<=V;++c)
    {
        cout<<adj[b][c]<<"| ";
    }
    cout<<endl;
}

for 循环条件应该检查b < V​​而c < V不是<=。当您bc == V您肯定在矩阵之外阅读时。

于 2011-04-13T01:50:14.350 回答