容器列表,在for循环中出现错误

Container list, I get error in for loop

本文关键字:错误 循环 for 列表      更新时间:2023-10-16

我想知道为什么我不能在这个方法中使用for循环,我在替换和插入方法中使用它,但在听到我在for循环行中得到一些错误。

 Contact return(const list<Contact> &listOf, int index) {
    for(list<Contact>::iterator it = listOf.begin(); it != listOf.end(); it++){
    }
    return Contact();   //dummy return. don't know what to do here
 }

我很感激一些关于如何实现代码的帮助,我要返回什么?

我的意思是我知道如何检查if语句以获得正确的对象,但我不知道在if语句中我要做什么以及要写什么来代替"Contact();"

为const列表使用const_iterator

Contact return_function(const list<Contact> &listOf, int index) {
    for(list<Contact>::const_iterator it = listOf.begin(); it != listOf.end(); it++){
    }
    return Contact();   //dummy return
 }

编辑。

您需要const_iterator,因为listOfconst

Contact return(const list<Contact> &listOf, int index) {
    //         ^^^^^---const container-----<
    //                                     ^
    // const_iterator--vvvvvv because of ->|
    for(list<Contact>::const_iterator it = listOf.begin(); it != listOf.end(); it++){

另外,您必须重命名您的函数,return是一个关键字。