我已经开始学习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";
Run Code Online (Sandbox Code Playgroud)
persons是的类型vector<Person>.我浏览所有条目并将名称与给定的搜索值进行比较.如果找到,我在foundPersons向量中添加人物.然后我打印No matches或找到的人数和表头.接下来,我将浏览所有找到的人并将其打印到控制台.
如果我添加两个人,例如"Jack Example"和"John Example",我搜索"Jack",它会找到"Jack"并打印出来.但随后程序停止了.Windows说"该程序已停止工作".编译期间或程序停止时不显示错误.
怎么了?
Ste*_*eve 12
你的循环不太正确,看起来你已经做了一个拼写错误,并从两个不同的列表引用迭代器.更改:
for(vector<Person>::iterator it = foundPersons.begin(); it != persons.end(); it++) {
Run Code Online (Sandbox Code Playgroud)
至
for(vector<Person>::iterator it = foundPersons.begin(); it != foundPersons.end(); it++) {
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |