我有一个这样的结构:
struct student {
string name;
int practical_grade;
int exam_grade;
int number_of_absences;
};
我已经创建了这个结构的列表。我可以访问所有int
个成员,但当我尝试访问name
字段时,我的程序会停止。知道为什么吗?
int main() {
string studentName;
int practicalGrade;
int examGrade;
int numberOfAbsences;
list <student> lista;
list <student>::iterator it = lista.begin();
cout<<"\tName: "; cin>>studentName;
cout<<"\tpractical grade: "; cin>>practicalGrade;
cout<<"\texam grade: "; cin>>examGrade;
cout<<"\tnumber of absences: "; cin>>numberOfAbsences;
lista.push_front({studentName,practicalGrade,examGrade,numberOfAbsences});
cout<< "elem: " << (*it).name;
cout<< "practical grade: " << (*it).practical_grade;
cout<< "\nexam: " << (*it).exam_grade <<' ' << (*it).number_of_absences <<"\n";
}
答案 0 :(得分:2)
开头时,列表为空。当您在空列表上调用lista.begin()
时,它会将迭代器返回到列表的末尾。然后,当您取消引用迭代器:(*it)
时,您将引用不指向任何元素的结束迭代器。这有不明确的行为。
解决方案:当列表实际包含元素时声明并初始化it
。或者干脆:
cout<< "elem: " << lista.front().name;
// ...
答案 1 :(得分:0)
评论已经回答了。在代码中:
lista.push_front({studentName,practicalGrade,examGrade,numberOfAbsences});
it = lista.begin(); // Update it
cout<< "elem: " << (*it).name;
cout<< "practical grade: " << (*it).practical_grade;
cout<< "\nexam: " << (*it).exam_grade <<' ' << (*it).number_of_absences <<"\n";