map/set 迭代器不可取消引用。多图容器问题
map/set iterator not dereferencable. Multimap container isse
我在尝试通过 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 << "\n\n";
}
问题可能出在这里:
if (used.find(to)->second != from) {
如果 to
不在 used
中,used.find()
将 return 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
我在尝试通过 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 << "\n\n";
}
问题可能出在这里:
if (used.find(to)->second != from) {
如果 to
不在 used
中,used.find()
将 return 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