我正在实现图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;
}
插入功能中这两行的问题:
*newEdge->vertex1 = v1;
*newEdge->vertex2 = v2;
vertex1
和vertex2
是未初始化的指针,它们没有指向内存中的有效位置,因此您尝试写入这些位置。我怀疑您希望vertex1
和vertex2
只是持有顶点ID的整数。
您的删除功能尝试进行类似的写入。您也应该修复该问题。