在 C++ 中创建一个随机生成的图形矩阵
Creating a randomly generated graph matrix in C++
所以,我一直在拼命地尝试制作这个随机生成的图形矩阵,但我无法让它工作,我也不知道为什么,一直出现段错误。这是我的代码:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
const int graph_size = 4;
int main(void)
{
bool** graph;
srand(time(0));
graph = new bool*[graph_size];
for(int i=0; i<graph_size; i++)
{
graph[i] = new bool[graph_size];
for(int j=0; j<graph_size; j++)
{
if(i==j){graph[i][j]=false;}
else{
graph[j][i] = (((rand()%100)/100.0) < 0.19);
graph[i][j] = graph[j][i];
}
cout << graph[i][j];
}
cout << endl;
}
}
您的问题是当您执行 graph[j][i]
时 j
大于 i
。发生这种情况时,您还没有为此索引分配数组,这会触发分段错误。
此外,正如@Jeffrey 所指出的,由于您构造了一个对称矩阵,因此您应该只计算上三角矩阵或下三角矩阵
您可以通过在开始时初始化图形并在 i 和 j 上添加条件来修复它:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
const int graph_size = 40;
int main(void)
{
bool **graph;
graph = new bool *[graph_size];
for (int i = 0; i < graph_size; i++)
graph[i] = new bool[graph_size];
srand(time(0));
for (int i = 0; i < graph_size; i++)
{
for (int j = 0; j < graph_size; j++)
{
if (i == j) graph[i][j] = false;
else if (i < j) // limits to upper triangular matrix
{
graph[j][i] = (((rand() % 100) / 100.0) < 0.19);
graph[i][j] = graph[j][i];
}
cout << graph[i][j];
}
cout << endl;
}
}
所以,我一直在拼命地尝试制作这个随机生成的图形矩阵,但我无法让它工作,我也不知道为什么,一直出现段错误。这是我的代码:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
const int graph_size = 4;
int main(void)
{
bool** graph;
srand(time(0));
graph = new bool*[graph_size];
for(int i=0; i<graph_size; i++)
{
graph[i] = new bool[graph_size];
for(int j=0; j<graph_size; j++)
{
if(i==j){graph[i][j]=false;}
else{
graph[j][i] = (((rand()%100)/100.0) < 0.19);
graph[i][j] = graph[j][i];
}
cout << graph[i][j];
}
cout << endl;
}
}
您的问题是当您执行 graph[j][i]
时 j
大于 i
。发生这种情况时,您还没有为此索引分配数组,这会触发分段错误。
此外,正如@Jeffrey 所指出的,由于您构造了一个对称矩阵,因此您应该只计算上三角矩阵或下三角矩阵
您可以通过在开始时初始化图形并在 i 和 j 上添加条件来修复它:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
const int graph_size = 40;
int main(void)
{
bool **graph;
graph = new bool *[graph_size];
for (int i = 0; i < graph_size; i++)
graph[i] = new bool[graph_size];
srand(time(0));
for (int i = 0; i < graph_size; i++)
{
for (int j = 0; j < graph_size; j++)
{
if (i == j) graph[i][j] = false;
else if (i < j) // limits to upper triangular matrix
{
graph[j][i] = (((rand() % 100) / 100.0) < 0.19);
graph[i][j] = graph[j][i];
}
cout << graph[i][j];
}
cout << endl;
}
}