简体   繁体   中英

c++ map iterator doesn't start from the first item

I'm trying to iterate over a map for some reason the iterator doesn't start from the first item.

const Noeud* origine = &noeuds.at(nomorigine);
map<string, Noeud>::iterator it;
origine->seeRoutes(); //Prints n5: n4 n6
it = origine->getRoutes().begin();
cout<<it->first<<endl; //Prints n4.
for(it = origine->getRoutes().begin(); it != origine->getRoutes().end(); it++){
    cout<<it->first<<endl; //Prints n6.
}

void Noeud::seeRoutes() const{
    cout<<getNom()<<": ";
    for(auto it = routes.begin(); it != routes.end(); it++){
        cout<<it->first<<" ";
    }
    cout<<endl;
}

I've tried using auto but the result is the same. What could be the cause of this problem?

Here is the class for Noeud:

class Noeud{
  public:
    string getNom() const;
    void setNom(const string& nom);
    void ajouterRoute(const string& nomRoute, const Noeud noeud);
    map<string, Noeud> getRoutes() const;
    void seeRoutes() const;

  private:
    string nom;
    map<string, Noeud> routes;
};

getRoutes() returns by value, that means what origine->getRoutes() returns is a temporary which will be destroyed after full-expression. After that it becomes dangled, any dereference on it leads to UB .

You can use a named variable to avoid this problem. eg

map<string, Noeud> m = origine->getRoutes();
it = m.begin();
...

And note that for the same reason, in the for loop origine->getRoutes() is invoked twice and returns two irrelevant objects. The iterators got from them are incompatible, comparing them is ill-formed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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