Reputation: 77
int main(){
vector<Monster*> Monsters;
vector<Monster*>::iterator iter;
Monsters.push_back(new Monster("Slim", 100));
Monsters.push_back(new Monster("Archer", 200));
Monsters.push_back(new Monster("Solider", 300));
Monsters.push_back(new Monster("Tank", 400));
Monsters.push_back(new Monster("Skeleton",500 ));
for (iter = Monsters.begin(); iter < Monsters.end(); iter++){
cout << *iter << endl;
}
system("pause");
return 0;
}
Hi all, So I made a Class called Monster, It have a a constructor which allow 2 variables, a string and and int (monster name , and monster health), Now I want to create 5 monsters with different name and Health, I put them in a vector and store it, but Now I want to use a Iterator to try to get all the information I stored in that Vector, but instead I get the memory address of it, I already used a "*iter" as a dereferencer, What have I done wrong? Sorry for got to mention I also have 2 functions in Monster class getname, and gethealth. which returns health and the name;
Upvotes: 1
Views: 899
Reputation: 1
try
cout << (*iter) ->getname;
cout << (*iter) ->gethealth;
or you can overload the '<<' operator in your Monster class
Upvotes: 0
Reputation: 15824
Since you are keeping MOnster pointer as type of your vector, you have use the following synax cout << (*iter)->name << endl;
to dereference the elements of Monster class.
Example is shown below:
class Monster{
public:
std::string name;
int age;
Monster( string s, int k): name(s),age(k)
{
}
};
int main(){
vector<Monster*> Monsters;
vector<Monster*>::iterator iter;
Monsters.push_back(new Monster("Slim", 100));
Monsters.push_back(new Monster("Archer", 200));
Monsters.push_back(new Monster("Solider", 300));
Monsters.push_back(new Monster("Tank", 400));
Monsters.push_back(new Monster("Skeleton",500 ));
for (iter = Monsters.begin(); iter != Monsters.end(); ++iter){
cout << (*iter)->name << endl;
}
}
Few other good practices:
always do pre-increment on iterators
Do end checking of container as iter != Monsters.end()
, it is valid in all kinds of iterators.
Upvotes: 3