list<LNode>::iterator minI(list<LNode>::iterator start,list<LNode>::iterator end)
{
list<LNode>::iterator min_index=start;
for(auto it=start;it!=end;it++)
{
if(it->len<min_index->len)
min_index=it;
}
return min_index;
}
在主函数中
..
cout<<(&(*vnode.begin()))<<endl;
auto min_it=minI(vnode.begin(),vnode.end());
cout<<(&(*vnode.begin()))<<endl;
cout<<(&(*min_it))<<endl;
char ch;
int i=min_it->i,j=min_it->j;
printf("\n%s\t%s\t%s\t%s\t%s\t",t1[i].from,t1[i].to,t1[i].flight,t2[j].city,t2[j].discount);
scanf("%s",&ch);
cout<<(&(*min_it))<<endl;
..
而前三个 cout 打印 0x600d88 最后一个 cout 打印 0x600d08 谁能给我解释一下原因??
,,
最佳答案
迭代器不会失效。
一般来说,标准容器上的迭代器只有在容器被修改时才会失效。在 list
的情况下,它们只有在它们引用的元素被删除时才会失效。
在第二段代码中,scanf
被赋予一个指向单个字符的指针,但会覆盖至少两个:用户输入的任何字符,后跟终止符。这给出了未定义的行为,这很可能会修改局部变量的值(如 min_it
)。尝试用更安全的 C++ 等价物替换它
std::string ch;
std::cin >> ch; // to read one word, or
std::getline(std::cin, ch); // to read a whole line
关于从列表中查找最小值的 C++ 函数。这个函数是否正确,因为返回的迭代器失效了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26729174/