当试图在multimap
中通过键获取值时,我得到此错误消息map/set iterator not dereferencable
。在这段代码中,我试图显示由邻接表(vector<Vertex*> vertexList
)表示的无方向图
void NonOrGraph::show() {
cout << endl;
multimap<int, int> used;
for (int i = 0; i < vertexList.size(); i++) {
if (vertexList[i]->adjMap.empty()) {
cout << vertexList[i]->index << " isolated";
} else {
for(map<Vertex*, int>::iterator it = vertexList[i]->adjMap.begin();
it != vertexList[i]->adjMap.end();
it++)
{
int from = vertexList[i]->index;
int to = it->first->index;
int weight = it->second;
used.insert(pair<int, int>(from, to));
if (used.find(to)->second != from) {
cout << from << " <--(" << weight << ")--> " << to << endl;
}
}
}
}
cout << "nn";
}
问题可能在这里:
if (used.find(to)->second != from) {
如果to
不在used
中,used.find()
将返回used.end()
,然后对其解引用。解引用end()
迭代器是一种未定义的行为,在这种情况下,它会给您一个运行时错误。
你必须先检查迭代器是否符合end()
:
std::multimap<int, int>::iterator multi_it = used.find(to);
if (multi_it != used.end() && multi_it->second != from) {
// ^^^^^^^^^^^^^^^^^^^^
// now, it's safe to dereference