C++新手求助:如何正确使用vector迭代器遍历Doctor指针容器
解决vector迭代器使用错误的问题
嘿,我来帮你搞定这个C++的小问题!你的代码里有两个关键错误导致了编译失败,咱们一步步来修正:
错误原因分析
- 类型名拼写不一致:你在
setDoctor里创建的是Doctor*类型的指针,但在showDoctors里错误写成了Doctors*(多了个s),C++对类型名的大小写和拼写要求严格,这会导致编译器识别不了正确的类型。 - 迭代器用法错误:
std::vector::at()方法的参数是整数类型的下标索引(比如0、1),但你传入的是vector<Doctor*>::iterator类型的迭代器对象,这完全不匹配,所以编译器报错无法转换参数类型。
修正后的代码
方法1:正确使用迭代器
void DoctorAdmin::showDoctors(){ cout << "Doctors:" << endl; cout << "Name" << "\t\t\t" << "Forename" << "\t\t\t" << "Sex" << endl; // 注意迭代器类型要和vector存储的类型匹配,是Doctor*不是Doctors* for (vector<Doctor*>::iterator i = doctors.begin(); i != doctors.end(); i++){ // 迭代器i是指向Doctor*的指针,用*i取出Doctor*对象 Doctor* doc = *i; cout << doc->getName() << "\t\t\t" << doc->getForename() << "\t\t\t" << doc->getSex() << endl; // 也可以更简洁:直接用i->调用成员函数,等价于(*i)-> // cout << (*i)->getName() << "\t\t\t" << (*i)->getForename() << "\t\t\t" << (*i)->getSex() << endl; } }
方法2:使用C++11及以后的范围for循环(更简洁,新手友好)
如果你用的是支持C++11或更高版本的编译器,推荐用范围for循环,代码更易读,还能避免迭代器的用法错误:
void DoctorAdmin::showDoctors(){ cout << "Doctors:" << endl; cout << "Name" << "\t\t\t" << "Forename" << "\t\t\t" << "Sex" << endl; // 遍历vector里的每个Doctor*指针 for (Doctor* doc : doctors){ cout << doc->getName() << "\t\t\t" << doc->getForename() << "\t\t\t" << doc->getSex() << endl; } }
额外提醒
另外,你用new创建了Doctor对象并存在vector里,记得在程序结束或者不需要这些医生对象时,遍历vector逐个delete指针,避免内存泄漏哦!比如:
void DoctorAdmin::cleanupDoctors() { for (Doctor* doc : doctors) { delete doc; } doctors.clear(); }
内容的提问来源于stack exchange,提问作者Grombaner
相关产品推荐
相关产品推荐

