Ggbeastboi
Ggbeastboi

Reputation: 77

Vector and Iterators, print out value instead of memory address

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

Answers (2)

bugbugs
bugbugs

Reputation: 1

try

cout << (*iter) ->getname;
cout << (*iter) ->gethealth;

or you can overload the '<<' operator in your Monster class

Upvotes: 0

Steephen
Steephen

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:

  1. always do pre-increment on iterators

  2. Do end checking of container as iter != Monsters.end(), it is valid in all kinds of iterators.

Upvotes: 3

Related Questions