C++正确使用向量迭代器

Gro*_*ner 0 c++ vector

我是C++的新手,我有一个医生的载体.
我用以下代码添加了一位新医生:

void DoctorAdmin::setDoctor(std::string lastname, std::string forename,
 Person::Sex sex){

    //Create new doctor
    Doctor* doc = new Doctor(lastname, forename, sex);

    //insert at the end of the vector
    doctors.push_back(doc);
}
Run Code Online (Sandbox Code Playgroud)

然后我想在控制台上显示他们的信息:

void DoctorAdmin::showDoctors(){

cout << "Doctors:" << endl;
cout << "Name" << "\t\t\t" << "Forename" << "\t\t\t" << "Sex" << endl;

for (vector<Doctor*>::iterator i = doctors.begin(); i != doctors.end(); i++){

    Doctors* doc = doctors.at(i);
    cout << doc->getName() << "\t\t\t" << doc->getForename() << "\t\t\t" 
         << doc->getSex() << endl;
}
Run Code Online (Sandbox Code Playgroud)

这样做后,我得到两个错误:

E0304   No instance of overloaded function "std::vector<_Ty, _Alloc>::at [mit _Ty=Doctors *, _Alloc=std::allocator<Doctors *>]" matches the argument list.

// and

C2664   "Doctors *const &std::vector<Doctors *,std::allocator<_Ty>>::at(const unsigned int) const" : cannot convert from Argument "std::_Vector_iterator<std::_Vector_val<std::_Simple_types<_Ty>>>" in "const unsigned int" 
Run Code Online (Sandbox Code Playgroud)

如何正确使用向量迭代器来避免这种情况?

Cal*_*eth 6

迭代器不像索引,它是指针式的.

for (vector<Arzt*>::iterator doc = aerzte.begin(); doc != aerzte.end(); doc++)
{
    cout << (*doc)->getName() << "\t\t\t" << (*doc)->getVorname() << "\t\t\t" 
         << (*doc)->getGeschlecht() << endl;
}
Run Code Online (Sandbox Code Playgroud)

看起来你很困惑什么时候你也需要new.大多数时候你不需要new

vector<Arzt> aerzte;

void ArztAdmin::anlegenArzt(std::string name, std::string vorname, Person::Geschlecht geschlecht){
    // Create new doctor at the end of the vector
    aerzte.emplace_back(name, vorname, geschlecht);   
}
Run Code Online (Sandbox Code Playgroud)

您还可以直接将引用绑定为循环变量

for (Arzt & doc : aerzte)
{
    cout << doc.getName() << "\t\t\t" << doc.getVorname() << "\t\t\t" 
         << doc.getGeschlecht() << endl;
}
Run Code Online (Sandbox Code Playgroud)