二维动态数组c++显示问题
2D Dynamic Array C++ Display Problem
我读过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;
}
是否保证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
,而不是<=
。当b
或c == V
你肯定是在矩阵外阅读
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '