我已经开始学习C ++,这让我很头疼。我写了一个简单的人“数据库”应用程序,由于某种原因,它在列出人员时失败了。
string search;
cout << "Give the name: ";
cin >> search;
vector<Person> foundPersons;
for(vector<Person>::iterator it = persons.begin(); it != persons.end(); it++) {
Person p = *it;
if(search == p.getFirstname() || search == p.getSurname()) {
foundPersons.push_back(p);
}
}
if(!foundPersons.empty()) {
cout << "Found " << foundPersons.size() << " person(s).\n\n";
cout << "Firstname\tSurname\t\tBirth year\n";
} else {
cout << "No matches.";
}
for(vector<Person>::iterator it = foundPersons.begin(); it != persons.end(); it++) {
Person p = *it;
cout << p.getFirstname() << "\t\t" << p.getSurname() << "\t" << p.getBirthYear() << "\n";
}
cout << "\n";
persons
是vector<Person>
的类型。我浏览所有条目并将名称与给定的搜索值进行比较。如果找到,我会在foundPersons
向量中添加此人。然后我打印No matches
或找到的人数和表头。接下来,我将浏览所有找到的人并将其打印到控制台。
如果我添加两个人,例如“Jack Example”和“John Example”,我搜索“Jack”,它会找到“Jack”并打印出来。但随后程序停止了。 Windows说“该程序已停止工作”。编译期间或程序停止时不会显示错误。
怎么了?
答案 0 :(得分:12)
你的循环不太正确,看起来你已经输了一个拼写错误并且正在引用来自两个不同列表的迭代器。变化:
for(vector<Person>::iterator it = foundPersons.begin(); it != persons.end(); it++) {
到
for(vector<Person>::iterator it = foundPersons.begin(); it != foundPersons.end(); it++) {