简体   繁体   English

映射/设置迭代器不可取。 多图容器isse

[英]map/set iterator not dereferencable. Multimap container isse

I'm geting this error message map/set iterator not dereferencable When trying to get value by key in multimap . 当尝试通过在multimap通过键获取值时,我收到此错误消息map/set iterator not dereferencable In this code I'm trying to show nonoriented graph represented by adjacency list ( vector<Vertex*> vertexList ) 在这段代码中,我试图显示由邻接表( vector<Vertex*> vertexList )表示的非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";

}

The problem is likely here: 问题可能在这里:

if (used.find(to)->second != from) {

If to is not in used , used.find() will return used.end() , which you then dereference. 如果to中未used used.find() ,则used.find()将返回used.end() ,然后您可以取消引用。 It is undefined behavior to dereference the end() iterator, which in this case manifests by giving you a runtime error. 取消引用end()迭代器是未定义的行为,在这种情况下,通过给您一个运行时错误来体现这一点。

You have to check the iterator against end() first: 您必须首先针对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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM