二维动态数组c++显示问题

2D Dynamic Array C++ Display Problem

本文关键字:数组 c++ 显示 问题 动态 二维      更新时间:2023-10-16

我读过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 filen";
       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();
}
//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];
} 

在初始化数据数组的代码中,我发现了两个明显的问题。首先,像这样的循环

    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];
} 

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

我不知道哪一行导致分割错误,但这里有一些事情要看:

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

是否保证uv小于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 < Vc < V,而不是<=。当bc == V你肯定是在矩阵外阅读