gpt4 book ai didi

c++ map迭代器不从第一项开始

转载 作者:行者123 更新时间:2023-11-30 02:21:51 25 4
gpt4 key购买 nike

由于某种原因迭代器没有从第一项开始,我正在尝试遍历 map 。

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;
}

我试过使用 auto 但结果是一样的。这个问题的原因可能是什么?

这是 Noeud 的类(class):

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() 按值返回,这意味着 origin->getRoutes() 返回的是 temporary完全表达后将被销毁。在那之后 it 变得悬垂,对它的任何取消引用都会导致 UB .

您可以使用命名变量来避免这个问题。例如

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

并且注意,出于同样的原因,在 for 循环中 origin->getRoutes() 被调用了两次并返回了两个不相关的对象。从他们那里得到的迭代器是不兼容的,比较他们是错误的。

关于c++ map迭代器不从第一项开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47898164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com