我有一个用 C++ 实现邻接矩阵的程序。
这是我的代码-
#include<iostream>
using namespace std;
void addEdge(int * add){
cout<<"Edge added successfully.\n";
*add = 1;
}
int main(){
int vertex;
cout<<"Enter number of vertices in the graph: ";
cin>>vertex;
int adjMat[vertex][vertex];
for(int i=0;i<vertex;i++){
for(int j=0;j<vertex;j++){
adjMat[i][j] = 0;
}
}
cout<<"\n";
cout<<"Add edges (from and to): ";
int from,to;
while(cin>>from>>to){
if((from >= vertex || from < 1) || (to >= vertex || to < 1)){
cout<"Warning: Out of bound index.\n";
}else{
addEdge(&adjMat[--from][--to]);
}
}
cout<<"\n";
for(int i=0;i<vertex;i++){
for(int j=0;j<vertex;j++){
cout<<adjMat[i][j]<<" ";
}
cout<<"\n";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在我的程序中,我错误地编写了一个错误并编译了该程序,但是 dev C++ 编译器没有为此给出错误并且程序运行良好。
这是那部分-
while(cin>>from>>to){
if((from >= vertex || from < 1) || (to >= vertex || to < 1)){
cout<"Warning: Out of bound index.\n";
}else{
addEdge(&adjMat[--from][--to]);
}
}
Run Code Online (Sandbox Code Playgroud)
我从其他编译器收到正确的错误消息。
编译器正在利用ostream的operator bool. 在 C++ 11 之前,它被实现为operator void *并返回 avoid*而不是bool导致语法上合法(但逻辑上不正确)的指针 < 指针比较。您已经找到了将运算符替换为现代bool版本的众多原因之一。
问题下方的评论者的建议不要使用如此古老的编译器,但根据您安装 Dev-C++ 的年龄,最简单的解决方案可能是打开 C++11 支持。如果你的 Dev-C++ 副本太旧了,而你仍然想使用它,我和 drescherjm 一起建议你用 msys2 的最新编译器替换它附带的编译器。这里有关于安装 msys2 及其 GCC 的很好的说明。
如果您想继续使用 Dev C++ 但不关心版本,这里是我所知道的最新版本的链接。它与 GCC 9.3 捆绑在一起,在撰写本文时它只有一年的历史并支持 C++17。