I have a list of pointers to classes:
list<AbsClient*> clients;
AbsClient could be 1 of 3: TempClient , RegisteredClient , VIPClient.
Inside AbsClient there’s a protected variable: phone_number.
I need to iterate through the clients list, and search for a specific phone number.
I tried this:
list<AbsClient*>::iterator iter;
for(iter=clients.begin();iter!=clients.end();++iter)
{
if(iter->phone_number == phone)
{
}
}
But it doesn’t give me access to the iter->phone_number:
error: expression must have pointer-to-class type
What’s wrong with this line?
P.S is it possible to use the stl::find function and somehow tell it to search by the “phone_number” variable?
Thank you
You can think of an iterator as a “pointer to an element” of your container. And the type of an element in your container is a
AbsClient*—another pointer. So, at least syntactically, you’re in a double-pointer situation, so you need to change how you dereference your iterator:Your post says that
phone_numberis a protected member, though, and you can’t access protected variables when you’re not inside that class or a derived class, so you either need to use an accessor method or change the visibility of your data member.And no, you can’t use
std::findto do this (at least not directly), but you can usestd::find_if:If you aren’t using C++11, then it’s a bit more verbose: