问题描述
我试图弄清楚如何在c ++中存储邻接矩阵。 下面是我要执行此操作的代码。
int main(){
//get input
int edges = -1,nodes = -1,source = -1;
cin >> nodes >> edges >> source;
vector<vector<int>> graph(nodes,vector<int>(nodes));'
//get adjacency matrix stored
for (int i = 0; i < nodes; i++){
for(int j = 0; j < nodes; j++){
cin >> graph[i][j];
}
}
//print out stored graph
for (int i = 0; i < nodes; i++){
for(int j=0; j < nodes; j++){
cout << graph[i][j];
}
cout << endl;
}
return 0;
}
输入为:
11 19 //first is num of nodes,second is num of edges
0 //source node
01110000000
10111000000
11010100000
11100010000
01000110100
00101011000
00011100011
00000100110
00001001010
00000011100
00000010000
我的目标是获得与输出相同的结果。但是,当我打印出图表时,得到以下信息:
11100000002147483647000000000
00000000000
00000000000
00000000000
00000000000
00000000000
00000000000
00000000000
00000000000
00000000000
00000000000
这告诉我图形的大小是正确的,因为它是11x11(逐节点大小)。但是,似乎代码只是从输入的第一行中获取值。
有人可以帮助我了解我哪里出了错吗?
解决方法
您的图形存储整数,因此当您读取图形数据时,行将被解析为整数。
graph[0][0]
来自01110000000
行,被解析为1'110'000'000
,适合32位整数。
graph[0][1]
处理下一行10111000000
,该行溢出(10'111'000'000
),因为它不适合32位整数。这将在流上设置错误条件,并将std::numeric_limits<T>::max()
存储在该值中。这是2147483647
部分来自(2'147'483'647
)的地方。后续输入全部失败,并将输入值设置为0,因为在流上设置了失败位。
要解决此问题,您需要输入字符。像
char ch;
cin >> ch;
graph[i][j] = ch != '0';
将0或1存储在图形中,将任何非0
输入视为1。您还希望跳过每行末尾的换行符。