Reputation: 7762
I have a class User
class User
{
public:
User();
User(string, string);
virtual string getRole();
void setPW(string);
void setID(string);
string getPW();
string getID();
protected:
string id;
string pw;
};
And several subclasses which inherit from User
class Customer : public User
{
public:
Customer();
Customer(string, string,string,string, string, string, string, string, string);
virtual string getRole();
string getSname();
string getFname();
string getTitle();
string getAddress();
string getTown();
string getCity();
string getPostalCode();
void setSname(string);
void setFname(string);
void setTitle(string);
void setAddress(string);
void setTown(string);
void setCity(string);
void setPostalCode(string);
private:
string sname;
string fname;
string title;
string address;
string town;
string city;
string postalcode;
};
All the information is stored inside a vector which contains pointers to the class User
vector<User*> userVector
How do i iterate through the vector of pointers to a class and call the respective methods of the class ??
If its a vector of User object , i can declare an iterator vector<User>::iterator p
, is there something equivalent for pointers to a object and how do i call the respective method of the class depending on the object
EDIT , this is what i have tried
vector<User*>::iterator p;
p=userVector.begin();
while ( p != userVector.end() )
{
//how to dereference
p++;
}
Upvotes: 1
Views: 3989
Reputation: 851
I recommend following 3 solutions in its priority order. You can select whatever you are comfortable with.
If you are using C++11 features, you can use range based loops for easy syntax. That's always advisable too.
Use for_each loop.
Otherwise, use like this which would be more optimal.
for( vector<User*>::iterator itr = userVector.begin(), itr_end = userVector.end(); itr != itr_end; ++itr )
{
std::cout << (*itr)->getRole() << std::endl;
}
Here you are not going to receive the end iterator each iteration of loop traversal.
Upvotes: 3
Reputation: 55415
Iterators behave like pointers in the way that they can be dereferenced and incremented (other operations depend on iterator category).
If you have a vector of pointers, then dereferencing its iterator gives you a pointer. That means you need to dereference once more to get to members. Assuming it
is the iterator:
(*it) -> getID()
// ^ ^^
// | second dereferencing
// first dereferencing
Upvotes: 1
Reputation: 2122
An iterator basically functions like a pointer, so you can consider vector<TYPE>::iterator
to be the equivalent of TYPE*
This means vector<TYPE*>::iterator
equates to TYPE**
So to get at your functions, you just need to dereference the iterator:
for( vector<User*>::iterator iter = userVector.begin(); iter != userVector.end(); ++iter )
{
std::cout << (*iter)->getRole() << std::endl;
}
Upvotes: 1