我正在尝试在 C++ 中实现有向图。但是,我的 RemoveEdge 函数有问题,在我调用该函数并在指针上使用 delete 运算符并将指针设置为nullptr
之后,它不会在函数范围之外为空。
我不确定我是否已经足够清楚地说明了我的问题,但也许一些代码会有所帮助。
图.h
template<class TVertex, class TEdge, class TWeight>
class Graph
{
protected:
std::list<Vertex<TVertex, TEdge, TWeight>*>* _Vertices;
std::list<Edge<TVertex, TEdge, TWeight>*>* _Edges;
public:
Graph();
int TotalVertices();
int TotalEdges();
std::list<Vertex<TVertex, TEdge, TWeight>*>* Vertices();
std::list<Edge<TVertex, TEdge, TWeight>*>* Edges();
Vertex<TVertex, TEdge, TWeight>* FindVertex(const TVertex&);
Vertex<TVertex, TEdge, TWeight>* InsertVertex(const TVertex&);
void RemoveVertex(const TVertex&);
Edge<TVertex, TEdge, TWeight>* FindEdge(const TEdge&);
Edge<TVertex, TEdge, TWeight>* InsertEdge(const TVertex&, const TVertex&, const TEdge&, const TWeight&);
void RemoveEdge(const TEdge&);
};
Graph.FindEdge()
template<class TVertex, class TEdge, class TWeight>
Edge<TVertex, TEdge, TWeight>* Graph<TVertex, TEdge, TWeight>::FindEdge(const TEdge& label)
{
Edge<TVertex, TEdge, TWeight>* edge = nullptr;
std::list<Edge<TVertex, TEdge, TWeight>*>::iterator it;
for(it = this->_Edges->begin(); it != this->_Edges->end(); ++it)
{
if(label == (*it)->Label())
{
edge = *it;
break;
}
}
return edge;
}
Graph.RemoveEdge()
template<class TVertex, class TEdge, class TWeight>
void Graph<TVertex, TEdge, TWeight>::RemoveEdge(const TEdge& label)
{
Edge<TVertex, TEdge, TWeight>* edge = this->FindEdge(label);
if(edge == nullptr)
return;
this->_Edges->remove(edge);
edge->Source()->RemoveEdge(edge);
edge->Destination()->RemoveEdge(edge);
// Problem is here, why isn't this working like I think it should?
delete edge;
edge = nullptr;
}
主文件
// created graph
// added vertices
// added edges
Edge<string, string, int>* e5 = graph->InsertEdge("Oshawa", "Toronto", "E5", 5);
graph->RemoveEdge("E5");
cout << ((e5 == nullptr) ? "null" : "not null") << endl; // this outputs not null
所以你可以看到我从图中删除边后我的程序崩溃了,由于某种原因,它not null
在执行 RemoveEdge 函数后输出。我不确定为什么会发生这种情况,我使用了 delete 运算符,并且之后我还明确地使指针为空。我在这里做错了什么?
是的,我确定找到了边缘,FindEdge 函数找到了正确的边缘对象并将其从适当的列表中删除,但删除运算符没有做我想要它做的事情。
感谢任何帮助。提前致谢。