简体   繁体   中英

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?

*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".

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)  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM