Reputation: 5273
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
Upvotes: 0
Views: 272
Reputation: 36517
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:
(*iter)->phone_number == phone
Your post says that phone_number
is 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::find
to do this (at least not directly), but you can use std::find_if
:
iter = std::find_if(clients.begin(), clients.end(),
[phone](AbsClient* cl) { return cl->phone_number == phone; });
If you aren't using C++11, then it's a bit more verbose:
struct MatchPhone {
explicit MatchPhone(PhoneNumber p) : phone(p) {}
bool operator()(AbsClient* cl) {
return cl->phone_number == phone;
}
PhoneNumber phone;
};
// ...
iter = std::find_if(clients.begin(), clients.end(), MatchPhone(phone));
// ...
Upvotes: 1