Michael Hang
Michael Hang

Reputation: 199

Dereferencing Iterator to Custom Struct Field

I have a vector players which I would like to iterate over. The 'player' struct appears as follows:

struct player { string name; int rating; };

I am using the iterator in a for loop to see if any of the 'players' have the name 'playerName' (a string).

for (vector<player>::iterator itr = players.begin(); itr != players.end(); ++itr) { if (playerName.compare(*itr->name) == 0) return true; } return false;

Unfortunately, I keep running into an error: 'error C2100: illegal indirection' (visual C++ 2008). I believe that I'm dereferencing the iterator incorrectly; is there a better way to do so?

Upvotes: 0

Views: 738

Answers (2)

Reuben Morais
Reuben Morais

Reputation: 1021

*itr->name is equivalent to (*itr)->name.

In your code, the type of (*itr) is player, not player*, so the compiler is basically telling you that you're trying to dereference something that isn't a pointer.

The correct way of doing that would be (*itr).name or itr->name, both meaning "dereference itr then access name".

Upvotes: 4

billz
billz

Reputation: 45420

I believe that I'm dereferencing the iterator incorrectly;

See corrected code:

if (playerName.compare(itr->name) == 0)

or

if (playerName.compare((*itr).name) == 0)  

Upvotes: 2

Related Questions