c++ - 抛出 C++ 异常
问题描述
我正在学习 C++,并且已经浪费了相当长的时间试图解决我遇到的错误的原因。当我运行下面的代码时,我抛出了一个异常。它发生在程序结束时,所以我相信它与 Edge 指针有关:
#include <iostream>
#include <vector>
#include <map>
using namespace std;
struct Edge {
int src, dest;
};
class Graph {
public:
int V, E;
Edge *edge = new Edge[E * sizeof(Edge)];
Graph(int Ver, int Edg);
};
Graph::Graph(int Ver, int Edg) {
V = Ver;
E = Edg;
}
Graph* createGraph(int V, int E) {
Graph* graph = new Graph(V,E);
return graph;
}
int find(int* parents, int val) {
if (parents[val] == -1)
return val;
return find(parents, parents[val]);
}
void Union(int *parents, int x, int y) {
parents[x] = y;
}
int isCycle(Graph* graph) {
int* parents = new int[graph->V * sizeof(int)];
memset(parents, -1, graph->V * sizeof(int));
for (int i = 0; i < graph->E; i++) {
int x = find(parents, graph->edge[i].src);
int y = find(parents, graph->edge[i].dest);
if (x == y) {
return 1;
};
Union(parents, x, y);
}
return 0;
}
int main()
{
int V = 9, E = 8;
Graph* graph = createGraph(V, E);
graph->edge[0].src = 0;
graph->edge[0].dest = 1;
graph->edge[6].src = 0;
graph->edge[6].dest = 6;
graph->edge[5].src = 0;
graph->edge[5].dest = 7;
graph->edge[1].src = 1;
graph->edge[1].dest = 2;
graph->edge[2].src = 3;
graph->edge[2].dest = 2;
graph->edge[3].src = 4;
graph->edge[3].dest = 3;
graph->edge[4].src = 4;
graph->edge[4].dest = 5;
graph->edge[7].src = 5;
graph->edge[7].dest = 7;
if (isCycle(graph))
cout << "graph contains cycle";
else
cout << "graph doesn't contain cycle";
return 0;
}
我几个月前才开始学习 C++,有人能帮我理解为什么我会遇到这个异常吗?
解决方案
Edge *edge = new Edge[E * sizeof(Edge)];
除非E
被初始化,否则这会将未初始化的变量乘以sizeof(Edge)
(这在其表面值上也是错误的,但我们稍后会讨论)。这是未定义的行为。
Graph::Graph(int Ver, int Edg) {
V = Ver;
E = Edg;
}
这还不够好。类成员的默认值(如果指定)用于在构造函数的主体开始运行之前对其进行初始化。
正确的方法是使用构造函数的初始化部分:
Graph::Graph(int Ver, int Edg) : V{Ver}, E{Ver}
{
}
这首先初始化V
,E
所以现在:
Edge *edge = new Edge[E * sizeof(Edge)];
所以这里,E
现在已经初始化,修复了这个问题。但这仍然有点不正确。很明显,根据其余代码,这应该是:
Edge *edge = new Edge[E];
在 C++ 中,当您希望声明一个由 4 个整数组成的数组时,您所要做的就是声明:
int n[4];
编译器负责将 4 乘以保存int
. 声明也是如此new
。如果您的目标是构建一个 # s 数组E
Edge
,那么不出所料:new Edge[E]
. 同样的错误在所示代码中多次出现。
推荐阅读
- fonts - Tesseract 未知字体训练
- xamarin - Xamarin 表单自定义页面呈现器数据绑定
- sql - SELECT 语句中的重复行
- python - 创建包含特定模式的所有变量的列表
- apache-camel - 文件端点中的条件文件名表达式
- html - 使用谷歌脚本将页面(链接)放在侧边栏中
- reactjs - 如何从 ReactJS 中的 OpenLayers Map 获取坐标?
- c# - 当 ItemSource 初始化为空时,Xamarin 表单控件未显示
- java - 将 Firebase 字符串数组检索到数组
- apache-zookeeper - Apache Flink Zookeeper 升级后检查点冲突