因此,我的任务是创建一个带有签名的函数:list
。 然后按出生顺序将该人的适当位置插入到列表中。 它的返回类型应该是迭代器。 我已尝试执行以下操作:
list<Person>::iterator SearchPos(list<Person> &MyList, Person &person)
{
}
int main()
{
char Dot;
string Dummy;
string Name;
int Day, Month, Year;
fstream MyFile;
MyFile.open("Kontakte.txt");
list<Person> BirthdayList; // Creating list of type Person
if(MyFile.is_open()) {cout << "File opened successfully." << endl;};
getline(MyFile, Name, ','); //Get line until "," is reached
MyFile >> Day >> Dot;
MyFile >> Month >> Dot;
MyFile >> Year;
getline(MyFile, Dummy); //Gets rid of \n char.
Person P1 (Name, Day, Month, Year);
SearchPos(&BirthdayList, &P1);
但是,即使没有searchpos()
函数的主体,也会出现错误:
“std::__cxx11::list
的rvalue
编辑非常感谢您对这个错误消息的帮助,我要花很长的时间才能搞清楚这个错误消息。 一旦我解决了关于如何实现SearchPos()的问题(或有人帮助我),我就会将问题标记为已回答。 我现在的想法是这样的:
list<Person>::iterator SearchPos(list<Person> &MyList, Person &person)
{
list<Person>::iterator pos;
for(pos = MyList.begin(); pos != MyList.end(); pos++)
{
//if the person to be checked was born earlier in the year than Person at pos return pos.
if(person.GetMonth() < pos->GetMonth()){return pos;}
//if same month but person earlier in the month then person should be inserted infront of pos.
if(person.GetMonth() == pos->GetMonth() && person.GetDay() < pos->GetDay()){return pos;}
//if none of above is true continue iterating
}
//the person that was referenced to is the oldest. Will Insert work here ?
return pos;
}
list<Person>::iterator pos;
getline(MyFile, Name, ','); //Get line until "," is reached
MyFile >> Day >> Dot;
MyFile >> Month >> Dot;
MyFile >> Year;
getline(MyFile, Dummy); //Gets rid of \n char.
cout << Dummy;
Person P2 (Name, Day, Month, Year);
pos = SearchPos(BirthdayList, P2);
BirthdayList.insert(pos);
main的其余部分仅根据您的解决方案进行了更改。 当前的错误消息是:调用“std::__cxx11::List::Insert(Sd::__cxx11::List::Iterator*)”没有匹配的函数
您需要像这样调用函数:
SearchPos(BirthdayList, P1);
正如注释中提到的,当函数查找引用时,您将参数作为指针传递。 使用符号(&;) 返回指向对象的指针。 我知道这可能会让人迷惑,而且似乎需要传入地址,因为您的函数接受引用,但您不需要这样做。 您只需在函数参数中将其声明为引用即可。
经过一些习惯之后,编译器错误实际上是清楚的。 也许这个能帮你破译。
“std::__cxx11::list&;”类型的非常量引用的初始化无效 来自类型为“std::__cxx11::list*”的rvalue
std::__cxx11::list
实际上是代码中的list
。 标准库只是添加了一些名称空间。 也许如果我们将示例切换到int
,会更清楚。
int SearchPos(int& index){} // let's define a function taking a reference to `int`.
int main() {
int my_index;
SearchPos(&my_index);
}
同样会导致
“Int(&;)”类型的非常量引用的初始化无效 来自类型为“int*”的rvalue
所以问题是您不能将int*
转换为int&;
。
int*
从哪里来? 您将获取类型int*
,因为运算符&; 返回int的地址,从而返回int的指针(int*
)。 (另外,返回的地址是rvalue
,因为它本身没有地址。)因此,要么确保输入的类型与方法的签名相对应:
int SearchPos(int* index){}
int main() {
int my_index;
SearchPos(&my_index);
}
,或者,您应该做的事情是,既然设置了签名,那么请确保您传递了一个引用:
int SearchPos(int& index){}
int main() {
int my_index;
SearchPos(my_index);
}