在为我的作业编写代码时,我遇到了一种奇怪的行为。代码很大,所以虽然没有必要,但我不会发布它。
问题是当我试图从向量中删除一个对象时,我遇到了分段错误。在尝试自己调试时,我发现了这一点:
如果我使用以下代码段执行我的代码,我的向量为空,然后第二行出现分段错误(因为向量为空)。
cout << this->adjacencyList.empty() << endl; // yeah, I'm working with graph
cout << *(this->adjacencyList[0]) << endl; // list has pointers
但是,当我删除第二行时,它显示向量不为空,然后继续。空向量的守卫不能保持它并且分段错误来了。
你对这种行为有什么想法吗?如果这一点仍然含糊不清,我可以发布我的完整代码作为编辑。
提前致谢。
编辑:
对于那些要求“多一点”的人。
void Node :: removeEdge (string destination) // removes an edge; edge is a class that contains a pointer to another node and its weight
{
bool deleted = false;
cout << *this << endl; // output stream operator is overloaded for node class and is working properly - shows it's label and edges - no error for an edge
cout << this->adjacencyList.empty() << endl;
// cout << *(this->adjacencyList[0]) << endl; // output stream operator is overloaded for edge class - error for an edge
if (!this->adjacencyList.empty())
{
for (vector <Edge *> :: iterator itr = this->adjacencyList.begin(); itr != this->adjacencyList.end(); ++itr)
{
if (((*itr)->getAdjacent())->getLabel() == destination) // segfault here
{
Edge *temp = *itr;
this->adjacencyList.erase (itr);
delete temp;
deleted = true;
}
}
}
if (!deleted)
throw EDGE_DOES_NOT_EXIST; // one of exceptions declared in enum somewhere in my code
}
第二次编辑:
注意:我不能更改标题(它们是由助手提供的),所以不要要求我更改。
如果您对完整代码感兴趣,可以在这里找到
http://pastebin.com/iCYF6hdP - Exceptions.h - 所有异常
http://pastebin.com/1fcgHGDa - Edge.h - 边缘类声明
http://pastebin.com/C2DD6e3D - Edge.cpp - 边缘类实现
http://pastebin.com/ZNqQ1iHE - Node.h - 节点类声明
http://pastebin.com/kaVtZ3SH - Node.cpp - 节点类实现
http://pastebin.com/A7Fwsi4m - Network.h - 图类声明
http://pastebin.com/02LX0rjw - Network.cpp - 图类实现
http://pastebin.com/MRMn0Scz - main.cpp - 样本主