mipmap
mipmap

Reputation: 221

Using class function on objects stored in List, accessed through iterator

I'm trying to print the names of some instances of Player, which is stored in a List<Player> players. What should I replace "Plop!" with to get this to work?

   list<Player>::iterator it;
   for(it=players.begin(); it != players.end(); ++it) cout << "Plop!" << " ";
   cout << endl;

I have tried

*it.getName();
*it->getName();

I have a feeling that the iterator should be handled differently than if it would be a normal pointer. Or perhaps the iterator *it does not contain the Player object at all?

Upvotes: 0

Views: 138

Answers (3)

davogotland
davogotland

Reputation: 2777

you need to dereference the iterator, as you're doing

*it

but the dereferencing drops to the left, if you know what i mean :) so you need to keep it in place with some parenthesis:

(*it).getName();

and don't forget the curly braces in the for loop!

Upvotes: 0

Joachim Isaksson
Joachim Isaksson

Reputation: 180917

It should be;

(*it).getName()

the . operator binds harder than *, which makes the compilation fail otherwise.

Upvotes: 1

Nim
Nim

Reputation: 33655

it->getName();

as long as Player has this method...

Upvotes: 1

Related Questions