gpt4 book ai didi

C++正确使用 vector 迭代器

转载 作者:太空宇宙 更新时间:2023-11-04 15:12:48 25 4
gpt4 key购买 nike

我是 C++ 的新手,我有一个医生 vector 。
我使用以下代码添加了一位新医生:

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);
}

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

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;
}

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

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"

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

最佳答案

迭代器不是索引类的,而是指针类的。

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;
}

您似乎对何时需要 事物感到困惑。大多数时候,您不需要 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);
}

也可以直接将引用绑定(bind)为循环变量

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

关于C++正确使用 vector 迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48298245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com