从列表中查找最小值的 C++ 函数。这个函数是否正确,因为返回的迭代器失效了

标签 c++ list templates pointers iterator

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/

相关文章:

css - 我该如何解决这些布局问题?

c++ - 当工件是库且标志影响 C 或 C++ header 时,功能标志/切换

c++ - 从文件中读取数据到C++中的多个数组

c++ - 从基指针列表循环 (OOD) 调用派生类方法

r - 如何将大列表中的 Entrez id 转换为基因符号并替换 R 中列表中的 entrez id?

python - 合并具有共同元素值的列表而不对其进行排序

css - Wicket 页面和模板中的小型 CSS 替换

c++ - 有没有办法在保存文件时设置qfiledialog的默认文件名

python - 如何将列表转换为元组列表?

c++ - 类的部分模板特化