【发布时间】:2014-03-26 02:44:44
【问题描述】:
我正在实现一个 Graph ADT 以用于不同的程序,并且我得到了我需要定义的这些“插入”和“删除”函数。他们应该创建一个带有两个顶点的 Edge(来自 Edge 结构)并将其插入/删除到更大的 Graph 中。当我在 main 中创建它的实例时,它运行良好,但是当我尝试调用 insert 或 remove 函数时,它会给出一个错误提示:
“COMP222 中 0x00A56C84 处的第一次机会异常 -- Program3.exe: 0xC0000005: 访问冲突写入位置 0xCDCDCDCD”。
关于我在这里可能做错什么导致此错误有什么想法吗?同样,主要问题是插入/删除,但我发布了其余部分以防万一。
EDGE STRUCT
struct Edge { //edge with vertices v1 and v2
int *vertex1;
int *vertex2;
};
GRAPH.H
#include "Graph.h"
#include <iostream>
Graph::Graph() {
graphSize = 0;
};
Graph::Graph(const string& file) {
text.open(file);
while(!text.eof()) {
char ch;
text.get(ch);
vertices.push_back(ch);
}
for(int i = 0;i < sizeof(vertices);i++) {
static_cast<int>(vertices.at(i));
}
}
void Graph::insert(int v1,int v2) {
Edge* newEdge = new Edge;
*newEdge->vertex1 = v1;
*newEdge->vertex2 = v2;
v1 = vertices.at(0);
v2 = vertices.at(2);
graphSize += 2;
};
void Graph::remove(int v1,int v2) {
Edge* delEdge = new Edge; //edge to be deleted
*delEdge->vertex1 = v1;
*delEdge->vertex2 = v2;
delete delEdge->vertex1;
delete delEdge->vertex2;
graphSize -= 2;
};
ostream& operator <<(ostream& verts,const Graph& graph) {
return verts;
};
MAIN FUNCTION -- problem seems to be with the test.insert and test.remove functions
#include "Graph.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
Graph test("Path to file...no problem here..."); //THIS WORKS FINE
test.insert(2,3); //INSERT/REMOVE CAUSE THE ERROR
test.remove(2,3);
system("PAUSE");
return 0;
}
【问题讨论】:
-
另外,您的删除功能没有意义。您正在创建一条新边,然后删除新创建的边的顶点指针?!我想,您想找到顶点为 v1,v2 的边并删除该边,对吧?
-
是的,这就是我想要做的。您建议将 vertex1 和 vertex2 更改为纯整数,谢谢。
-
我更改了删除功能。我忘记了我定义了一个向量来存储边,所以我搜索了边,如果顶点匹配,我将其删除。现在一切正常。感谢您的帮助!
标签: c++ graph-theory access-violation abstract-data-type