如何创建返回list迭代器的SearchPos函数?含调用错误排查
问题分析与修复方案
你遇到的这个错误其实很典型——函数参数的类型和你传入的实参类型完全不匹配。咱们拆解来看:
- 你的
SearchPos函数声明里,两个参数都是引用类型:list<Person>&(绑定到list对象的引用)和Person&(绑定到Person对象的引用)。 - 但你在
main函数里调用它的时候,却传入了指针:&BirthdayList是取list对象的地址,得到的是list<Person>*类型;&P1是取Person对象的地址,得到的是Person*类型。
C++编译器没办法自动把指针转换成非const的引用,所以就抛出了那个invalid initialization的错误。
第一步:修正函数调用
你只需要直接传入对象本身就行,不需要取地址,因为引用参数本来就是用来直接绑定到对象上的:
// 错误写法:传了指针 // SearchPos(&BirthdayList, &P1); // 正确写法:直接传对象 auto insertPosition = SearchPos(BirthdayList, P1);
第二步:完善函数逻辑(按你的需求)
你后来补充的函数框架是对的,这里可以再补充一个常见的按出生日期查找插入位置的实现逻辑(假设你的Person类有day、month、year成员变量):
list<Person>::iterator SearchPos(list<Person> &MyList, Person &person) { list<Person>::iterator pos; // 遍历链表,找到第一个出生日期晚于当前person的位置 for (pos = MyList.begin(); pos != MyList.end(); ++pos) { if (person.year < pos->year || (person.year == pos->year && person.month < pos->month) || (person.year == pos->year && person.month == pos->month && person.day < pos->day)) { break; } } // 如果遍历到末尾,说明当前person是最晚的,返回end()作为插入位置 return pos; }
修正后的完整main函数片段
int main() { char Dot; string Dummy; string Name; int Day, Month, Year; fstream MyFile; MyFile.open("Kontakte.txt"); list<Person> BirthdayList; // 创建Person类型的list if(MyFile.is_open()) {cout << "File opened successfully." << endl;}; getline(MyFile, Name, ','); //读取直到","的内容 MyFile >> Day >> Dot; MyFile >> Month >> Dot; MyFile >> Year; getline(MyFile, Dummy); //去除换行符 Person P1 (Name, Day, Month, Year); // 修正后的调用 auto insertPos = SearchPos(BirthdayList, P1); // 用返回的迭代器插入元素 BirthdayList.insert(insertPos, P1); return 0; }
内容的提问来源于stack exchange,提问作者Reseve
相关产品推荐
相关产品推荐

